Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#反射,使用MakeGenericMethod和具有';新的();类型约束_C#_Reflection_Generics_Generic Method - Fatal编程技术网

C#反射,使用MakeGenericMethod和具有';新的();类型约束

C#反射,使用MakeGenericMethod和具有';新的();类型约束,c#,reflection,generics,generic-method,C#,Reflection,Generics,Generic Method,我尝试使用MethodInfo MakeGenericMethod,如下所示: foreach (var type in types) { object output = null; var method = typeof (ContentTypeResolver).GetMethod("TryConstruct"); var genmethod = method.MakeGenericMet

我尝试使用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];
        }
针对以下通用方法:

    public static bool TryConstruct<T>(string from, out IThingy result) where T : IThingy, new()
    {
        var thing = new T();
        return thingTryConstructFrom(from, out result);
    }
publicstaticbooltryconstruct(stringfrom,out-IThingy-result),其中T:IThingy,new()
{
var thing=newt();
返回thingTryConstructFrom(从,输出结果);
}
我遇到的问题是,我在MakeGenericMethod行上得到一个arguement异常,因为我传递的类型不是“new()”

有办法解决这个问题吗??
谢谢

否。您只能使用满足
i仅
new
约束的类型参数创建封闭构造的TryConstruct方法。否则,您将破坏TryConstruct契约:当您调用TryConstruct并且它到达
newt()
行时会发生什么?如果没有t()构造函数,那么您就违反了类型安全性

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