根据子类指定基类抽象方法的返回类型
我有以下结构:
abstract class Base {
public abstract List<...> Get(); //What should be the generic type?
}
class SubOne : Base {
public override List<SubOne> Get() {
}
}
class SubTwo : Base {
public override List<SubTwo> Get() {
}
}
我想创建一个抽象方法,该方法返回具体子类是什么类。 因此,正如您从示例中看到的,SubOne
中的方法应返回 List
,而 SubTwo
中的方法应返回 列出
。
我在基类中声明的签名中指定什么类型?
[更新]
感谢您发布的答案。
解决方案是使抽象类变得通用,如下所示:
abstract class Base<T> {
public abstract List<T> Get();
}
class SubOne : Base<SubOne> {
public override List<SubOne> Get() {
}
}
class SubTwo : Base<SubTwo> {
public override List<SubTwo> Get() {
}
}
I have the following structure:
abstract class Base {
public abstract List<...> Get(); //What should be the generic type?
}
class SubOne : Base {
public override List<SubOne> Get() {
}
}
class SubTwo : Base {
public override List<SubTwo> Get() {
}
}
I want to create an abstract method that returns whatever class the concrete sub class is. So, as you can see from the example, the method in SubOne
should return List<SubOne>
whereas the method in SubTwo
should return List<SubTwo>
.
What type do I specify in the signature declared in the Base class ?
[UPDATE]
Thank you for the posted answers.
The solution is to make the abstract class generic, like such:
abstract class Base<T> {
public abstract List<T> Get();
}
class SubOne : Base<SubOne> {
public override List<SubOne> Get() {
}
}
class SubTwo : Base<SubTwo> {
public override List<SubTwo> Get() {
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你的抽象类应该是通用的。
如果需要引用不带泛型类型参数的抽象类,请使用接口:
Your abstract class should be generic.
If you need to refer to the abstract class without the generic type argument, use an interface:
尝试这个:
Try this:
我不认为你可以让它成为特定的子类。 不过你可以这样做:
I don't think you can get it to be the specific subclass. You can do this though:
如果您的基类由于各种原因不能通用,那么此方法可能会很有用:
如果您无法向子类添加接口,并且仍然无法将泛型添加到基本类型此方法可能有用:
(不幸的是,您不能使 GetImpl 受到保护,因为不允许帮助程序类位于基类内部)
在这两种情况下,这都将按预期工作:
If you have an situation where your base class cannot be generic for various reasons, this method might be useful:
If you are unable to add interface to your sub classes, and still unable to add generics to the Base type this method might be useful:
(Unfortunately you cannot make the GetImpl protected, since the helper class is not allowed to be inside the base class)
In both cases, this will work as expected: