如何检查如果一个类型提供参数的构造函数? [英] How do I check if a type provides a parameterless constructor?
问题描述
我想检查是否在运行时已知的类型提供参数的构造函数。在键入
类没有取得什么前途,所以我假设我必须使用反射?
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?
推荐答案
的键入
类的<em>是的反思。你可以这样做:
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);
这将返回如果参数的构造函数不存在空。
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);
有对价值类型的一个警告,其中<一个HREF =http://msdn.microsoft.com/en-us/library/aa288208%28VS.71%29.aspx>不允许有一个默认的构造函数。您可以检查您是否已经使用 Type.IsValueType
属性,创建一个使用实例 Activator.CreateInstance(类型)
;
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屋!