System.Reflection.Emit 动态实现接口

Posted valeb

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了System.Reflection.Emit 动态实现接口相关的知识,希望对你有一定的参考价值。

 class Program
    {
        static void Main(string[] args)
        { 
            var obj = EmitHelper.ImplInterface<IPerson>();
            obj.say();
            obj.sayHi();
        }
    }
      
    public interface IPerson
    {
        void say();
        void sayHi();
    }
     
    public class EmitHelper
    {
        public static T ImplInterface<T>()
        { 
            string name = "ImplInterface";
            AssemblyName asmName = new AssemblyName(name);
            Type classType = typeof(T); 
            var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndCollect);
            var modelBuider = assemblyBuilder.DefineDynamicModule(name + ".dll"); 
            var typeBuilder = modelBuider.DefineType("impl_" + classType.Name); 
            typeBuilder.AddInterfaceImplementation(typeof(T));

            var methods = classType.GetMembers();
            foreach (var method in methods)
            {
                var methodBuilder = typeBuilder.DefineMethod(method.Name, MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final, null, Type.EmptyTypes); 
                typeBuilder.DefineMethodOverride(methodBuilder, typeof(T).GetMethod(method.Name));
              
                //TODO:以下是方法体的生成,还得再分析与修改
                ILGenerator il = methodBuilder.GetILGenerator();
                il.Emit(OpCodes.Ldstr, "接口:" + method.Name);
                il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));
                il.Emit(OpCodes.Ret);

            } 
            Type objType = typeBuilder.CreateType();
            object obj = Activator.CreateInstance(objType);  
            return (T)obj;
        }
    } 

  

以上是关于System.Reflection.Emit 动态实现接口的主要内容,如果未能解决你的问题,请参考以下文章

Protobuf-net & IL2CPP - System.Reflection.Emit 不受支持

反射-Emit

MyDAL - 组件适用范围说明

学习 CIL (MSIL) 的最佳资源是啥

JS动画之缓动函数分析及动画库

css+js可以让图片动起来吗