如何检查类型是否提供无参数构造函数?

maf*_*afu 97 .net c# reflection constructor types

我想检查运行时已知的类型是否提供无参数构造函数.这Type堂课并没有带来任何好处,所以我假设我必须使用反思?

Ale*_*x J 164

Type堂课反思.你可以做:

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);
Run Code Online (Sandbox Code Playgroud)

如果无参数构造函数不存在,它将返回null.


如果您还想查找私有构造函数,请使用稍长的:

var constructor = theType.GetConstructor(
  BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, 
  null, Type.EmptyTypes, null);
Run Code Online (Sandbox Code Playgroud)

值类型有一个警告,不允许使用默认构造函数.您可以使用该Type.IsValueType属性检查是否具有值类型,并使用创建实例Activator.CreateInstance(Type);

  • 上面的评论. (3认同)
  • 这不会找到私人ctors (2认同)

naw*_*fal 13

type.GetConstructor(Type.EmptyTypes) != null
Run Code Online (Sandbox Code Playgroud)

会失败struct的.更好地扩展它:

public static bool HasDefaultConstructor(this Type t)
{
    return t.IsValueType || t.GetConstructor(Type.EmptyTypes) != null;
}
Run Code Online (Sandbox Code Playgroud)

成功甚至enums都有默认的无参数构造函数.由于未进行反射调用,因此值类型也略微加快.


Hen*_*man 12

是的,你必须使用Reflection.但是你在使用时已经这样做了GetType()

就像是:

var t = x.GetType();
var c = t.GetConstructor(new Type[0]);
if (c != null) ...
Run Code Online (Sandbox Code Playgroud)


Bro*_*ass 8

这应该工作:

   myClass.GetType().GetConstructors()
                    .All(c=>c.GetParameters().Length == 0)
Run Code Online (Sandbox Code Playgroud)

  • 这不是我的意思,但是请不要删除-这是一个相关问题,是一个很好的信息。 (2认同)
  • 事实上,OP请求的正确表达式应该是“myClass.GetType().GetConstructors().Any(c=>c.GetParameters().Length == 0)”。请注意使用 **Any** 而不是 **All**。 (2认同)