[英]determine whether a generic type has a standard constructor
Let T
be a generic type. 设
T
为通用类型。 I would like to do something like this: 我想做这样的事情:
T x = default(T);
if (T has standard constructor)
x = new T();
Of course, one could restrict T
to types having such a constructor, but I do not want ot exclude value types. 当然,可以将
T
限制为具有这种构造函数的类型,但我不希望排除值类型。
How can you do that? 你怎么能这样做?
You'll have to use reflection: 你必须使用反射:
ConstructorInfo ci = typeof(T).GetConstructor(Type.EmptyTypes);
if (ci != null)
x = (T)ci.Invoke(null);
You can also use Activator.CreateInstance<T>()
, but that will throw an exception if the constructor doesn't exist. 您也可以使用
Activator.CreateInstance<T>()
,但如果构造函数不存在,则会抛出异常。
edit: 编辑:
The question states that 问题表明
Of course, one could restrict T to types having such a constructor, but I do not want not exclude value types.
当然,可以将T限制为具有这种构造函数的类型,但我不想排除值类型。
Using the constraint shown below does not limit T
to Reference types. 使用下面显示的约束不会将
T
限制为引用类型。 If you need to support other constructors for a different reason, please update your question. 如果您因其他原因需要支持其他构造函数,请更新您的问题。
(pre-edit: may not apply to question after all) (预编辑:毕竟可能不适用于问题)
You are looking for a new
constraint (also referred to as a parameter-less constructor constraint) : 您正在寻找
new
约束 (也称为无参数构造函数约束) :
class YourClass<T> where T : new()
{
public T doSomething()
{
return new T();
}
}
T
is definitely allowed to be a value type, for instance: T
绝对允许为值类型,例如:
YourClass<char> c = new YourClass<char>();
char result = c.doSomething();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.