如何检查无参数构造函数的类型?

MTR*_*MTR 6 .net c# reflection constructor

因为我想避免异常,我想检查一个类型是否具有无参数构造函数.我怎样才能做到这一点?

我需要这样的东西:

bool HasDefaultConstructor<TT>(TT source)
{
   return ???;
}
Run Code Online (Sandbox Code Playgroud)

编辑:我想创建一个与源相同类型的对象,如果它没有默认构造函数,我想使用默认(TT).

我现在拥有的是:

        static TT CreateObject<TT>(TT source)
    {
        try
        {
            if(!HasDefaultConstructor<TT>(source))
            {
                return default(TT);
            }
            return (TT)Activator.CreateInstance(source.GetType());
        }
        catch(Exception ex)
        {
            Trace.WriteLine("Exception catched!\r\n" + ex);
        }
        return default(TT);
    }
    static bool HasDefaultConstructor<TT>(TT source)
    {
        ConstructorInfo c = typeof(TT).GetConstructor(new Type[] { });

        return c != null;
    }
Run Code Online (Sandbox Code Playgroud)

但是检查给了我真实的并且CreateInstance抛出了异常

没有无参数的构造函数

解:

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

有许多递归函数和迭代涉及到这种方式,已经调用了错误的泛型函数HasDefaultConstructor(带有类型对象).使用非泛型函数就可以了.

谢谢大家的建设性帮助.

Adi*_*ter 10

GetConstructor(Type.EmptyTypes) 将返回无参数构造函数,如果不存在则返回null,因此您可以:

return typeof(TT).GetConstructor(Type.EmptyTypes) != null;
Run Code Online (Sandbox Code Playgroud)

编辑

我猜你的问题是,TTsource.GetType()实际上是两个不同的类型.source.GetType()可能派生自TT但没有无参数构造函数.所以你真正需要做的是检查source.GetType():

bool HasDefaultConstructor(Type t)
{
   return t.GetConstructor(Type.EmptyTypes) != null;
}

if(!HasDefaultConstructor(source.GetType()))
    ...
Run Code Online (Sandbox Code Playgroud)


Pat*_*man 8

使用反射来检查类型是否具有无参数构造函数.用途Type.GetConstructor:

bool HasDefaultConstructor<TT>()
{
    ConstructorInfo c = typeof(TT).GetConstructor(new Type[] { });
    // A constructor without any types defined: no parameters

    return c != null;
}
Run Code Online (Sandbox Code Playgroud)

如果您只想创建实例TT,请使用new约束:

TT CreateUsingDefaultConstructor<TT>() where TT : new()
{
    return new TT();
}
Run Code Online (Sandbox Code Playgroud)

正如Jeppe Stig Nielsen建议的那样,您可以使用此代码来查找不是的构造函数public.在我看来,你应该只使用它作为最后的手段!

typeof(TT).GetConstructor( BindingFlags.Instance
                           | BindingFlags.NonPublic
                           | BindingFlags.Public
                         , null
                         , new Type[] { }
                         , null
                         )
Run Code Online (Sandbox Code Playgroud)

  • 当然,如果您也接受非公共零参数构造函数,请尝试`typeof(TT).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,null,new Type [] {},null) `. (3认同)