C# 根据子类从基类指定抽象方法的返回类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/675857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Specifying the return type of an abstract method from a Base Class according to a Sub Class
提问by Andreas Grech
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>
.
我想创建一个抽象方法,该方法返回具体子类是什么类。因此,正如您从示例中看到的,in 中的方法SubOne
应该返回,List<SubOne>
而 in 中的方法SubTwo
应该返回List<SubTwo>
。
What type do I specify in the signature declared in the Base class ?
我在 Base 类中声明的签名中指定什么类型?
[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() {
}
}
采纳答案by recursive
Your abstract class should be generic.
你的抽象类应该是通用的。
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() {
}
}
If you need to refer to the abstract class without the generic type argument, use an interface:
如果需要引用没有泛型类型参数的抽象类,请使用接口:
interface IBase {
//common functions
}
abstract class Base<T> : IBase {
public abstract List<T> Get();
}
回答by eglasius
I don't think you can get it to be the specific subclass. You can do this though:
我认为你不能让它成为特定的子类。你可以这样做:
abstract class Base<SubClass> {
public abstract List<SubClass> Get();
}
class SubOne : Base<SubOne> {
public override List<SubOne> Get() {
throw new NotImplementedException();
}
}
class SubTwo : Base<SubTwo> {
public override List<SubTwo> Get() {
throw new NotImplementedException();
}
}
回答by John Feminella
Try this:
尝试这个:
public abstract class Base<T> {
public abstract List<T> Foo();
}
public class Derived : Base<Derived> { // Any derived class will now return a List of
public List<Derived> Foo() { ... } // itself.
}
回答by Mitch Wheat
public abstract class Base<T>
{
public abstract List<T> Get();
}
class SubOne : Base<SubOne>
{
public override List<SubOne> Get() { return new List<SubOne>(); }
}
class SubTwo : Base<SubTwo>
{
public override List<SubTwo> Get() { return new List<SubTwo>(); }
}