创建其构造函数需要参数的泛型类型的实例? [英] Create instance of generic type whose constructor requires a parameter?

查看:70
本文介绍了创建其构造函数需要参数的泛型类型的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 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 一个无参数的构造函数,然后通过成员变量填写所有内容,我才能做到这一点。在我的实际代码中(不是关于水果的),这是不切实际的。

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-

这样看来那时就无法通过任何约束来解决。从答案中可以找到三种候选解决方案:

-Update-
So it seems it can't be solved by constraints in any way then. From the answers there are three candidate solutions:


  • 工厂模式

  • Reflection

  • Activator

我倾向于认为反射是最不干净的一种,但我无法在另一种之间做出决定

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上使用new()约束只是使编译器检查公共无参数构造时,用于创建类型的实际代码是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.

您需要确保自己已存在的特定构造函数以及这种要求可能是代码的味道(或者,您应该尝试在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆