没有新的约束创建T的新实例 [英] Create a new instance of T without the new constraint
问题描述
如果一个人想创建一个通用的新实例,该新的约束需要定义,像这样:
公共牛逼的someMethod< T>()其中T:新的()
{
返回新T();
}
是否有可能,使用反射,在没有新的创建T的实例约束,像这样(含有伪代码):
公共牛逼的someMethod< T>()
{
如果(T有一个默认的构造函数)
{
返回T的新实例;
}
,否则
{
返回工厂< T> .CreateNew();
}
}
使用 Activator.CreateInstance()
这一点。请参见 http://msdn.microsoft.com/en-us/library/system.activator .createinstance.aspx 有关如何使用此方法的详细信息。基本上,你做的是:
VAR OBJ =(T)Activator.CreateInstance(typeof运算(T));
您可以验证是否通过 GetConstructors有一个默认的构造函数()
方法:
VAR构造= typeof运算(T).GetConstructors();
如果你发现具有零参数的构造函数,你可以使用激活.CreateInstance
方法。否则,您可以使用工厂< T> .CreateNew()
法
编辑:
要找出直接不带任何参数的构造函数是否存在,你可以使用下面的检查:
如果(typeof运算(T).GetConstructor(Type.EmptyTypes)!= NULL)
{
// ...
If one wants to create a new instance of a generic, the new constraint needs to be defined, like so:
public T SomeMethod<T>() where T : new()
{
return new T();
}
Is it possible, using reflection, to create an instance of T without the new constraint, like so (contains pseudocode):
public T SomeMethod<T>()
{
if (T has a default constructor)
{
return a new instance of T;
}
else
{
return Factory<T>.CreateNew();
}
}
Use Activator.CreateInstance()
for this. See http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx for more information on how to use this method. Basically, what you do is:
var obj = (T)Activator.CreateInstance(typeof(T));
You can verify whether it has a default constructor by using the GetConstructors()
method:
var constructors = typeof(T).GetConstructors();
If you find a constructor that has zero parameters, you can use the Activator.CreateInstance
method. Otherwise, you use the Factory<T>.CreateNew()
method.
EDIT:
To find out directly whether a constructor without any parameters exist, you can use the following check:
if (typeof(T).GetConstructor(Type.EmptyTypes) != null)
{
// ...
这篇关于没有新的约束创建T的新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!