C # 中的泛型——如何创建带参数的变量类型的实例?

我有一个泛型类,在这里我想用泛型类型实例化一个对象。我想为类型的构造函数使用一个参数。

我的代码:

public class GenericClass<T> where T : Some_Base_Class, new()
{
public static T SomeFunction(string s)
{
if (String.IsNullOrEmpty(s))
return new T(some_param);
}
}

我得到一个错误的

new T(some_param)

‘ T’: 在创建变量实例时不能提供参数 类别

有什么办法吗?

39102 次浏览

Take a look at Activator.CreateInstance. For instance:

var instance = Activator.CreateInstance(typeof(T), new object[] { null, null });

Obviously replacing the nulls with appropriate values expected by one of the constructors of the type.

If you receive a compiler error about cannot convert object to type T, then include as T:

var instance = Activator.CreateInstance(typeof(T),
new object[] { null, null }) as T;