如何检查如果一个类型提供参数的构造函数? [英] How do I check if a type provides a parameterless constructor?

查看:126
本文介绍了如何检查如果一个类型提供参数的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查是否在运行时已知的类型提供参数的构造函数。在键入类没有取得什么前途,所以我假设我必须使用反射?

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 =htt​​p://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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆