Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.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# 将泛型类型构造函数转换为非泛型类型构造函数_C#_Generics_Reflection - Fatal编程技术网

C# 将泛型类型构造函数转换为非泛型类型构造函数

C# 将泛型类型构造函数转换为非泛型类型构造函数,c#,generics,reflection,C#,Generics,Reflection,例如,我有课 class TestClass<T> { } class测试类 { } 我有一些方法接收这个类的构造函数。 我想用一些泛型参数调用该构造函数,而不需要再次调用MakeGenericType和GetConstructor方法 static void Main() { var ctor = typeof (TestClass<>).GetConstructors().First(); Invoke(ctor ); } static void

例如,我有课

class TestClass<T>
{
}
class测试类
{
}
我有一些方法接收这个类的构造函数。 我想用一些泛型参数调用该构造函数,而不需要再次调用MakeGenericType和GetConstructor方法

static void Main()
{
    var ctor = typeof (TestClass<>).GetConstructors().First();
    Invoke(ctor );
}

static void Invoke(ConstructorInfo ctor)
{
    //ctor.Invoke() - it will not work because TestClass has a generic parameter.
    // I want something like ctor.MakeGenericMethod(typeof(int)).Invoke();
}
static void Main()
{
var ctor=typeof(TestClass).GetConstructors().First();
调用(ctor);
}
静态void调用(ConstructorInfo-ctor)
{
//ctor.Invoke()-它将不起作用,因为TestClass有一个泛型参数。
//我需要类似于ctor.MakeGenericMethod(typeof(int)).Invoke()的东西;
}
有可能吗? 谢谢

找到了解决方案:

MethodBase.GetMethodFromHandle(ctor.MethodHandle, typeof(TestClass<int>).TypeHandle);
MethodBase.GetMethodFromHandle(ctor.MethodHandle,typeof(TestClass.TypeHandle));

var result=Activator.CreateInstance(typeof(TestClass).MakeGenericType(typeof(int))
或者如果您想找到
ConstructorInfo
typeof(TestClass).MakeGenericType(typeof(int)).GetConstructors()…
您必须提供
T
。您必须像
typeof(TestClass).GetConstructors()那样调用它。