指示generics返回动态类型的对象

这个问题是我原来问题的后续问题。

假设我有以下generics类(简化!^ _ ^):

class CasterClass where T : class { public CasterClass() { /* none */ } public T Cast(object obj) { return (obj as T); } } 

哪个能够将对象转换为指定的类型。

不幸的是,在编译时,我不知道我将要使用哪种类型,所以我必须通过reflection来实例化这个类,如下所示:

 Type t = typeof(castedObject); // creating the reflected Caster object object CasterObj = Activator.CreateInstance( typeof(CasterClass).MakeGenericType(t) ); // creating a reflection of the CasterClass' Cast method MethodInfo mi = typeof(CasterClass).GetMethod("Cast"); 

问题是,一旦我使用mi.Invoke()调用方法,它将返回一个对象类型的输出,而不是特定类型的T实例(因为reflection)。

有没有办法通过reflection调用方法返回一个动态类型,如上图所示? 我很确定.NET 3.5没有强制转换为动态类型的设施(或者更确切地说,它是非常不切实际的)。

非常感谢!

如果你可以控制你将要使用的类,让它们都实例化一个包含你将要调用的方法的接口,一旦你实例化,就转换为接口。

我也用同样的想法发布了你上一个问题的答案。

只需将任何类型传递给ObjectCreateMethod,您将获得一个动态方法处理程序,稍后您可以使用它来将通用对象转换为特定类型,并调用CreateInstance。

 ObjectCreateMethod _MyDynamicMethod = new ObjectCreateMethod(info.PropertyType); object _MyNewEntity = _MyDynamicMethod.CreateInstance(); 

打电话给这堂课:

 using System.Reflection; using System.Reflection.Emit; public class ObjectCreateMethod { delegate object MethodInvoker(); MethodInvoker methodHandler = null; public ObjectCreateMethod(Type type) { CreateMethod(type.GetConstructor(Type.EmptyTypes)); } public ObjectCreateMethod(ConstructorInfo target) { CreateMethod(target); } void CreateMethod(ConstructorInfo target) { DynamicMethod dynamic = new DynamicMethod(string.Empty,typeof(object),new Type[0], target.DeclaringType); ILGenerator il = dynamic.GetILGenerator(); il.DeclareLocal(target.DeclaringType); il.Emit(OpCodes.Newobj, target); il.Emit(OpCodes.Stloc_0); il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Ret); methodHandler = (MethodInvoker)dynamic.CreateDelegate(typeof(MethodInvoker)); } public object CreateInstance() { return methodHandler(); } }