在C#泛型 - 我怎么可以创建一个变量类型与参数的实例? [英] Generics in C# - how can I create an instance of a variable type with an argument?
问题描述
我有一个泛型类,在这里我想实例化泛型类型的对象。我想使用该类型的构造函数的参数。
我的code:
公共类GenericClass< T>其中T:Some_Base_Class,新的()
{
公共静态ŧSomeFunction(字符串s)
{
如果(String.IsNullOrEmpty(多个))
返回新的T(some_param);
}
}
我得到了一个错误
新T(some_param)
的'T':无法创建变量的实例时提供的参数
键入的
块引用>任何想法我怎么能这样做呢?
解决方案在看看<一个href=\"http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx\"><$c$c>Activator.CreateInstance$c$c>.例如:
VAR实例= Activator.CreateInstance(typeof运算(T),新的对象[] {NULL,NULL});
显然与该类型的构造函数之一有望适当的值替换
空
秒。如果您收到有关
编译器错误不能转换对象类型T
,然后包括为T
:VAR实例= Activator.CreateInstance(typeof运算(T)
新的对象[] {NULL,NULL})为T;I've got a generics class, where I want to instantiate an object with the generic type. I want to use an argument for the constructor of the type.
My code:
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); } }
I get an error on the
new T(some_param)
'T': cannot provide arguments when creating an instance of a variable type
Any ideas how can I do this?
解决方案Take a look at
Activator.CreateInstance
. For instance:var instance = Activator.CreateInstance(typeof(T), new object[] { null, null });
Obviously replacing the
null
s 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 includeas T
:var instance = Activator.CreateInstance(typeof(T), new object[] { null, null }) as T;
这篇关于在C#泛型 - 我怎么可以创建一个变量类型与参数的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!