[英]Dynamically instantiate class
我试图动态实例化抽象类的类后代,但是激活器迫使我将构造函数覆盖到每个后代。 有办法避免这种情况吗?
PS:我需要在构造函数中传递参数,只有在那里可以写,否则将始终被读取!
有办法避免这种情况吗?
简短的回答:是的,当你在派生类中定义没有构造,使用的(抽象)基类的构造函数。 定义一个时,必须重新定义所有构造函数。
并非没有解决方法。
编辑:对不起,我错了,它仅适用于无参数构造函数。
正在使用受保护的无参数构造函数和静态Create方法:
public abstract class Duck {
private string _DucksParam0;
public string DucksParam0 {
get {
return _DucksParam0;
}
}
// Using protected, this constructor can only be used within the class instance
// or a within a derived class, also in static methods
protected Duck() { }
public static DuckT Create<DuckT>(string param0)
where DuckT : Duck
{
// Use the (implicit) parameterless constructor
DuckT theDuck = (DuckT)Activator.CreateInstance(typeof(DuckT));
// This is now your "real" constructor
theDuck._DucksParam0 = param0;
return theDuck;
}
}
public class Donald : Duck {
}
用法( dotnetfiddle ):
public class Program
{
public void Main()
{
Duck d = Duck.Create<Donald>("Hello World");
Console.WriteLine(d.DucksParam0);
}
}
构造函数不是继承的 ,因此,如果必须通过带有那些参数的构造函数实例化子对象,则需要在基本上执行base(p1, p2, ..., pn)
的子类中编写一个新的构造函数。
查看您的代码,似乎您的构造函数只分配/初始化字段,因此,只要您适当地控制它,就没有理由为什么不能在构造函数之外的某个地方执行该操作。 这可能是一个长镜头,但我觉得这更是您想要的:
public abstract class Parent
{
protected bool foo
{
get;
private set; // just set the property setter as private
}
protected Parent() {
// protected so all instances are created through createAnotherX
// note that nothing is initialized here!
}
public abstract int Enter(); // To override in child classes
// Option 1: use generics
public static T createAnother1<T>(bool f) where T : Parent, new()
{
T p = new T();
p.foo = f;
return p;
}
// Option 2: use the runtime type
public static Parent createAnother2(Type t, bool f)
{
Parent p = Activator.CreateInstance(t) as Parent;
p.foo = f;
return p;
}
// Examples
public static void Main()
{
Parent p1 = Parent.createAnother1<Child>(true);
Parent p2 = Parent.createAnother2(typeof(Child), true);
}
}
// the child class only has to worry about overriding Enter()
public class Child : Parent
{
public override int Enter()
{
return 1;
}
}
请注意,由于默认构造函数受到保护,因此必须通过createAnotherX
实例化对象。 此外,根据您的注释,请注意已定义该属性,以便只有您可以设置值,这是在显式忽略设置程序时尝试在代码中执行的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.