C#Reflection,使用MakeGenericMethod和具有'new()'类型约束的方法

Dve*_*Dve 3 c# generics reflection generic-method

我正在尝试使用MethodInfo MakeGenericMethod,如下所示:

        foreach (var type in types)
        {
            object output = null;
            var method = typeof (ContentTypeResolver).GetMethod("TryConstruct");
            var genmethod = method.MakeGenericMethod(type);
            var arr = new object[] { from, output };
            if ((bool)genmethod.Invoke(null, arr))
                return (IThingy)arr[1];
        }
Run Code Online (Sandbox Code Playgroud)

针对以下通用方法:

    public static bool TryConstruct<T>(string from, out IThingy result) where T : IThingy, new()
    {
        var thing = new T();
        return thingTryConstructFrom(from, out result);
    }
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是我在MakeGenericMethod行上得到了一个争论异常,因为我传递的类型不是'new()'

这有什么办法?谢谢

ito*_*son 5

号你只能用符合类型参数封闭构造TryConstruct方法IThingynew约束.否则你就会打败TryConstruct合同:当你调用TryConstruct并且它命中时会发生什么new T()?有不会一个T()构造函数,所以你已经违反类型安全.

在将其传递给MakeGenericMethod之前,您需要检查该类型是否具有公共默认构造函数.如果需要使用非默认构造函数实例化类型,则需要创建一个新方法或TryConstruct重载,可能是使用Activator.CreateInstance而不是new T().