c# emit 动态实现接口
2021-02-20 14:18
标签:inter nta ilo odi blog rgs efi UI post c# emit 动态实现接口 标签:inter nta ilo odi blog rgs efi UI post 原文地址:https://www.cnblogs.com/tiancai/p/8283182.htmlusing 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);
}
}
}
上一篇:c# emit 实现类的代理