c# emit 动态实现接口

using System;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;


namespace TestEmit{

   public interface IPerson{
        void SayHello();
    
    }

   class Person2 {
       public void SayHello() {

           Console.WriteLine("i am person2");
       }
   }

    class Test2
    {
        static void Main(string[] args)
        {
            IPerson p = (IPerson)CreateType();
            p.SayHello();

 
            Console.ReadLine();
        }



        public static object CreateType()
        {
            AssemblyName assemblyName = new AssemblyName("assemblyName");
            AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("PersonModule", "Person.dll");
            TypeBuilder typeBuilder = moduleBuilder.DefineType("Person", TypeAttributes.Public);
            //*添加所实现的接口
            typeBuilder.AddInterfaceImplementation(typeof(IPerson));

          //实现方法
            MethodBuilder mbIM = typeBuilder.DefineMethod("SayHello",
           MethodAttributes.Public | MethodAttributes.HideBySig |
               MethodAttributes.NewSlot | MethodAttributes.Virtual |
               MethodAttributes.Final,
           null,
           Type.EmptyTypes);
       
            ILGenerator il = mbIM.GetILGenerator();
            il.Emit(OpCodes.Ldstr, "The SayHello implementation of IPerson");
            il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine",
                new Type[] { typeof(string) }));
            il.Emit(OpCodes.Ret);
            typeBuilder.DefineMethodOverride(mbIM, typeof(IPerson).GetMethod("SayHello"));
 //添加方法
            //MethodBuilder sayHelloMethod = typeBuilder.DefineMethod("SayHello", MethodAttributes.Public, null, null);
     

            //ILGenerator ilOfSayHello = sayHelloMethod.GetILGenerator();
            //ilOfSayHello.Emit(OpCodes.Ldstr, "蝈蝈");
            //ilOfSayHello.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));
            //ilOfSayHello.Emit(OpCodes.Call, typeof(Console).GetMethod("ReadLine"));
            ////没有返回值所有加OpCodes.Pop
            //ilOfSayHello.Emit(OpCodes.Pop);
            //ilOfSayHello.Emit(OpCodes.Ret);
            Type personType = typeBuilder.CreateType();
            assemblyBuilder.Save("Person.dll");
            object obj = Activator.CreateInstance(personType);
            MethodInfo methodInfo = personType.GetMethod("SayHello");
            
            methodInfo.Invoke(obj, null);
            return Activator.CreateInstance(personType);
        }

    }


 
}

 

posted @ 2018-01-14 13:31  甜菜波波  阅读(4020)  评论(1编辑  收藏  举报