码迷,mamicode.com
首页 > 其他好文 > 详细

System.Reflection.Emit 动态实现接口

时间:2020-04-29 18:10:20      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:har   deb   build   efi   run   接口   typeof   call   tor   

 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 动态实现接口

标签:har   deb   build   efi   run   接口   typeof   call   tor   

原文地址:https://www.cnblogs.com/valeb/p/12803426.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!