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()那样调用它。