[英]Create derived classes with parameterized constructors using factory method with type parameter
I have an abstract base class and a derived class. 我有一个抽象基类和一个派生类。 Let us call them
Base
and Derived
. 让我们称它们为
Base
和Derived
。
Base
has the constructor: Base
具有构造函数:
public Base(int number)
{
// do something with number
}
and the Derived
class will always have the constructor ( even though this cannot be ensured through an interface , this is nevertheless the case in my program): 并且
Derived
类将始终具有构造函数( 即使无法通过接口确保该构造函数,但在我的程序中仍然是这种情况):
public Derived(int number) : base(number)
{
// do some other stuff
}
Now, I would like a factory method to create objects derived from Base
, which should be called like this: 现在,我想使用一种工厂方法来创建从
Base
派生的对象,该对象应这样调用:
Base.Create<Derived>(someNumber);
But I do not know how to implement this method in a correct fashion. 但是我不知道如何以正确的方式实现此方法。 I think the most elegant solution would be to do something like this:
我认为最优雅的解决方案是执行以下操作:
public static T Create<T>(int number) where T : Base, new(int)
{
return new T(number);
}
But it seems that C# does not support the parameterized constructor constraint new(int)
, only the parameterless one. 但是似乎C#不支持参数化构造函数约束
new(int)
,仅不支持参数化。 This solution would have been so clear and it expresses exactly what I want. 这个解决方案将是如此清晰,它确切表达了我想要的。 Oh well..
那好吧..
Instead, I could basically switch on the type parameter and create and instance of the correct type like this: 相反,我基本上可以打开type参数并创建和创建正确类型的实例,如下所示:
public static Base Create<T>(int number) where T : Base, new(int)
{
if (typeof(T) == typeof(Derived))
{
return new Derived(number);
}
// and so on for all other derived types
}
But this requires me to update the method every single time I make a new derived class, which is unfortunate. 但这要求我每次创建新的派生类时都要更新该方法,这是不幸的。 Besides,
typeof(T) == typeof(Derived)
seems way too hackish. 此外,
typeof(T) == typeof(Derived)
似乎过于骇客。 Also, with this approach it seems the return type of the factory method will have to be Base
instead of T
, which is also unfortunate. 同样,使用这种方法,似乎工厂方法的返回类型必须是
Base
而不是T
,这也是不幸的。 I could just as easily resort to using enums instead of a type parameter in that case. 在这种情况下,我可以轻松地使用枚举而不是类型参数。
I wonder if there is a better way to achieve what I want? 我想知道是否有更好的方法来实现我想要的?
You can use an Activator to create an instance: 您可以使用激活器来创建实例:
public static T Create<T>(int number) where T : Base
{
return (T) Activator.CreateInstance(typeof (T), number);
}
In this case you will not need to update the method if you create a new derived class. 在这种情况下,如果创建新的派生类,则无需更新方法。 This assumes that you always have a constructor which takes a single integer parameter.
这假定您始终有一个采用单个整数参数的构造函数。 If such constructor does not exist you will get a runtime exception.
如果不存在此类构造函数,则将获得运行时异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.