Instructing a generic to return an object of a dynamic type

前端 未结 2 652
暗喜
暗喜 2021-01-28 18:48

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 CasterCla         


        
2条回答
  •  终归单人心
    2021-01-28 18:56

    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();
        }
    }
    

提交回复
热议问题