创建泛型类型的实例? [英] Create instance of generic type?
问题描述
如果 BaseFruit
有一个接受 INT重量
构造函数,我可以实例化一个水果在通用这样的方法?
If BaseFruit
has a constructor that accepts an int weight
, can I instantiate a piece of fruit in a generic method like this?
public void AddFruit<T>()where T: BaseFruit{
BaseFruit fruit = new T(weight); /*new Apple(150);*/
fruit.Enlist(fruitManager);
}
这是例子后面添加注释。看来我只能这样做,如果我给 BaseFruit
参数的构造函数,然后通过成员变量填写的一切。在我真正的code(不是水果),这是非常不现实的。
An example is added behind comments. It seems I can only do this if I give BaseFruit
a parameterless constructor and then fill in everything through member variables. In my real code (not about fruit) this is rather impractical.
- 更新 -
因此,似乎它不能被限制以任何方式解决然后。从答案有三个候选方案:
-Update-
So it seems it can't be solved by constraints in any way then. From the answers there are three candidate solutions:
- 在工厂模式
- 反射
- 激活
我倾向于认为反思是最干净的,但我不能在另外两个之间的决定。
I tend to think reflection is the least clean one, but I can't decide between the other two.
推荐答案
此外一个简单的例子:
return (T)Activator.CreateInstance(typeof(T), new object[] { weight });
请注意,使用T上的新的()约束只是让编译器检查一个公共的无参数的构造函数在编译的时候,实际的code用来创建类型为Activator类。
Note that using the new() constraint on T is only to make the compiler check for a public parameterless constructor at compile time, the actual code used to create the type is the Activator class.
您需要确保自己有关的具体构造存在,而这种需求可能是一个code气味(或者更确切地说,你应该只是尽量避免在C#中的当前版本)。
You will need to ensure yourself regarding the specific constructor existing, and this kind of requirement may be a code smell (or rather something you should just try to avoid in the current version on c#).
这篇关于创建泛型类型的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!