如何检查类型是否提供无参数构造函数? [英] How do I check if a type provides a parameterless constructor?
问题描述
我想检查在运行时已知的类型是否提供无参数构造函数.Type
类没有产生任何有希望的东西,所以我假设我必须使用反射?
I'd like to check if a type that is known at runtime provides a parameterless constructor. The Type
class did not yield anything promising, so I'm assuming I have to use reflection?
推荐答案
Type
类是 反射.你可以这样做:
The Type
class is reflection. You can do:
Type theType = myobject.GetType(); // if you have an instance
// or
Type theType = typeof(MyObject); // if you know the type
var constructor = theType.GetConstructor(Type.EmptyTypes);
如果无参数构造函数不存在,它将返回 null.
It will return null if a parameterless constructor does not exist.
如果您还想查找私有构造函数,请使用稍长的:
If you also want to find private constructors, use the slightly longer:
var constructor = theType.GetConstructor(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null, Type.EmptyTypes, null);
<小时>
值类型有一个警告,不是允许有一个默认构造函数.您可以使用 Type 检查您是否具有值类型.IsValueType
属性,并使用 Activator.CreateInstance(Type)
;
There's a caveat for value types, which aren't allowed to have a default constructor. You can check if you have a value type using the Type.IsValueType
property, and create instances using Activator.CreateInstance(Type)
;
这篇关于如何检查类型是否提供无参数构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!