1. 定义接口
public interface IPerson
{
    void Speak(string msg);
}
  1. 实现比较简单,直接上代码 :)
    public class Builder
    {

        public string Test()
        {
            var myType= BuilderClass();
            var myObject =(IPerson) Activator.CreateInstance(myType);
            myObject.Speak("test");
            return "";
        }

        public Type BuilderClass()
        {
            //构建一个Type
            var type= typeof(IPerson);
            TypeBuilder typeBuilder = TypeBuilder(type.Name.TrimStart('I'));

            //创建构造函数
            var constructor= typeBuilder.DefineDefaultConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
            
            //继承接口
            typeBuilder.AddInterfaceImplementation(type);
            
            //实现接口
            var methodList= type.GetMethods();
            foreach(var methodInfo in methodList)
            {
                //创建一个方法
                MethodBuilder methodBuilder= typeBuilder.DefineMethod(methodInfo.Name, 
                    MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual |MethodAttributes.Final
                    , methodInfo.ReturnType
                    ,methodInfo.GetParameters().Select(key=>key.ParameterType).ToArray());

                //对方法里面的功能进行实现
                BuilderMethod(methodBuilder);
                typeBuilder.DefineMethodOverride(methodBuilder, methodInfo);
            }
            return typeBuilder.CreateType();
        }

        public void BuilderMethod(MethodBuilder methodBuilder)
        {
            methodBuilder.SetImplementationFlags(MethodImplAttributes.IL);
            var il= methodBuilder.GetILGenerator();
            var method= typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) });
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Call, method);
            il.Emit(OpCodes.Ret);
        }
        

        private  TypeBuilder TypeBuilder(string typeSignature)
        {
            var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(Guid.NewGuid().ToString()), AssemblyBuilderAccess.Run);
            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
            return moduleBuilder.DefineType(typeSignature,TypeAttributes.Public);
        }
    }

posted on 2021-07-13 14:06  好怀念啊  阅读(122)  评论(0编辑  收藏  举报