如何检查类型是否提供无参数构造函数? [英] How do I check if a type provides a parameterless constructor?

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

问题描述

我想检查在运行时已知的类型是否提供无参数构造函数.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屋!

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