标签: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; } }
标签:har deb build efi run 接口 typeof call tor
原文地址:https://www.cnblogs.com/valeb/p/12803426.html