抽象方法,返回派生类的一个实例
问题描述:
是否有可能创建一个必须返回派生类的一个实例,一个抽象的方法?我可以这样做:
Is it possible to create an abstract method that must return an instance of the derived class? I can do this:
abstract class Base
{
public abstract Base GetObj();
}
class Derived : Base
{
public Derived() { }
public override Base GetObj()
{
return new Derived();
}
}
但我想知道是否有一种方法可以做到这使得派生:: GetObj()
被迫返回导出
?
感谢
答
使用泛型要实现这一点:
Using generics should make this possible:
abstract class Base<T>
where T : Base<T>
{
public abstract T GetObj();
}
class Derived : Base <Derived>
{
public Derived() { }
public override Derived GetObj()
{
return new Derived();
}
}
您甚至可以简化这个更(如果所有的派生的实例与默认构造函数创建):
You could even simplify this even more (if all of the derived instances are created with default constructors):
abstract class Base<T>
where T : Base<T>, new()
{
public static T GetObj()
{
return new T();
}
}
class Derived : Base<Derived>
{
public Derived() { }
}