Instructing a generic to return an object of a dynamic type
This question is sort of a follow-up to my original question here.
Let's say that I have the following generic class (simplifying! ^_^):
class CasterClass<T> where T : class
{
public CasterClass() { /* none */ }
public T Cast(object obj)
{
return (obj as T);
}
}
Which has the ability to cast an object into a specified type.
Unfortunately, at compile-time, I don't have the luxury of knowing what types exactly I'll have to work with, so I'll have to instantiate this class via reflection, like so:
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");
Problem is, once I call the method using mi.Invoke(), it will return an object typed output, instead of the specifically-typed T instance (because of reflection).
Is there any way to have a method invoked through reflection return a dynamic type, as illustrated above? I'm pretty sure that .NET开发者_JAVA百科 3.5 doesn't have the facilities to cast into a dynamic type (or rather, it would be very impractical).
Many thanks!
If you have control over the classes you'll be working with, have them all instantiate an interface that contains the methods you'll be calling and once you instantiate, cast to the interface.
I also posted an answer to your previous question with the same idea.
Just pass any type to ObjectCreateMethod, and you'll get a dynamic method handler, which you can later use to cast a generic object into a specific type, invoking CreateInstance.
ObjectCreateMethod _MyDynamicMethod = new ObjectCreateMethod(info.PropertyType);
object _MyNewEntity = _MyDynamicMethod.CreateInstance();
Call this class:
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();
}
}
精彩评论