【发布时间】:2023-03-04 02:34:01
【问题描述】:
是否可以获得当前派生类的新实例,该实例正在调用基本抽象类的函数?例如:
class Bar1 : Foo
{
}
class Bar2 : Foo
{
}
abstract class Foo
{
public Foo CreateAnotherInstance()
{
return new Bar1/Bar2(); // depending on the calling derived class
}
}
应该导致:
Bar1 bar1 = new Bar1();
Bar2 bar2 = new Bar2();
Foo bar1_2 = bar1.CreateAnotherInstance(); // Should be a new Bar1 instance
Foo bar2_2 = bar1.CreateAnotherInstance(); // Should be a new Bar2 instance
我发现创建实例的唯一方法是一个抽象方法,其中实例是在每个派生类中创建的,例如:
class Bar1 : Foo
{
public override Foo CreateAnotherInstance()
{
return new Bar1();
}
}
class Bar2 : Foo
{
public override Foo CreateAnotherInstance()
{
return new Bar2();
}
}
abstract class Foo
{
public abstract Foo CreateAnotherInstance();
}
但这样一来,我必须为每个派生类创建方法。
对于这个问题有更简单的解决方案吗?
【问题讨论】:
-
你为什么需要它?
bar1已经是Bar1的一个实例 -
如果派生类具有公共无参数构造函数,
return Activator.CreateInstance(GetType());将起作用。 -
是的,请参阅 mjwills 的链接或MSDN
-
@Pedro 您应该将解决方案添加为自我回答,而不是在原始帖子中。
标签: c# abstract-class derived-class