分享

ILGenerator创建对象

 tiancaiwrk 2019-03-01

using System;

using System.Reflection;

using System.Reflection.Emit;

 

[MenuItem("Toole/Test", false)]

        public static void Test()

        {

            var call = CreateCtor(typeof(AA));

            var tag = call.Invoke();

            if(tag != null)

            {

            }

        }

        public class AA

        {

            public int a = 100;

        }

        public static ObjectActivator CreateCtor(Type type)

        {

            if(type == null)

            {

                throw new NullReferenceException("type");

            }

            ConstructorInfo emptyConstructor = type.GetConstructor(Type.EmptyTypes);

            var dynamicMethod = new DynamicMethod("CreateInstance", type, Type.EmptyTypes, true);

            ILGenerator ilGenerator = dynamicMethod.GetILGenerator();

            ilGenerator.Emit(OpCodes.Nop);

            ilGenerator.Emit(OpCodes.Newobj, emptyConstructor);

            ilGenerator.Emit(OpCodes.Ret);

            return (ObjectActivator)dynamicMethod.CreateDelegate(typeof(ObjectActivator));

        }

        public delegate object ObjectActivator();

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多