使用Type对象创建generics

我正在尝试使用Type对象创建generics类的实例。

基本上,我会在运行时拥有不同类型的对象集合,因为无法确定知道它们究竟属于哪种类型,我想我将不得不使用Reflection。

我正在做的事情如下:

Type elType = Type.GetType(obj); Type genType = typeof(GenericType).MakeGenericType(elType); object obj = Activator.CreateInstance(genType); 

哪个好,好。 ^ ___ ^

问题是,我想访问我的GenericType 实例的方法,我不能这样做,因为它被键入为对象类。 我找不到将obj强制转换为特定的GenericType 的方法,因为这首先是问题(即,我不能放入像:)这样的东西

 ((GenericType)obj).MyMethod(); 

应该怎样解决这个问题?

非常感谢! ^ ___ ^

您必须继续使用Reflection来调用实际方法:

 // Your code Type elType = Type.GetType(obj); Type genType = typeof(GenericType<>).MakeGenericType(elType); object obj = Activator.CreateInstance(genType); // To execute the method MethodInfo method = genType.GetMethod("MyMethod", BindingFlags.Instance | BindingFlags.Public); method.Invoke(obj, null); 

有关更多信息,请参阅Type.GetMethod和MethodBase.Invoke 。

一旦你开始reflection游戏,你必须玩它直到结束。 该类型在编译时是未知的,因此您无法强制转换它。 您必须通过reflection调用该方法:

 obj.GetType().InvokeMember( "MyMethod", BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, obj, null ); 

在C#3.5中,您必须使用Type.GetMethodMethodInfo.Invoke来调用该方法。

在C#4中,您可以使用dynamic关键字并在运行时绑定到该方法。

最直接的方法是从GenericType中提取非generics超类型(基类或接口),其中包含您要为此目的公开的方法:

 class GenericType : GenericBase { ... } class GenericBase { abstract void MyMethod(); } 

如果不这样做,请按照@Aaronaught的建议使用reflection来访问方法本身。

创建实例后,只需执行以下操作:

 MethodInfo method = genType.GetMethod("MyMethod"); method.Invoke(obj, null); 

如果您知道要调用的方法的签名,则不仅可以使用此处其他示例中所示的MethodInfo.Invoke() ,还可以创建一个允许更有效调用的委托(如果需要调用相同的方法)使用Delegate.CreateDelegate()

我不确定你的类型有多大变化,或者你是否可以控制你将在其中调用的方法,但是创建一个接口来定义你将调用哪些函数可能会很有用。 因此,在创建实例后,您可以转换为接口并调用您需要的任何函数。

所以创建你的标准接口(如果你能控制它们,你需要在每种类型中实现):

 interface IMyInterface { void A(); int B(); } class One : IMyInterface { ... implement A and B ... } Type elType = Type.GetType(obj); Type genType = typeof(GenericType<>).MakeGenericType(elType); IMyInterface obj = (IMyInterface)Activator.CreateInstance(genType); obj.A();