下载app免费领取会员
假设有一个ITest接口,它有两个实现分别是TestClass1,和TestClass2,这时候如果需要一个TestClass4类但是现有程序里又没有这个类,就可以在运行时生成一个这样的类
这个应该是可以用来实现AOP,
public interface ITest
{
void Run();
}
public class TestClass1 : ITest
{
public void Run()
{
Console.WriteLine("TestClass1");
}
}
public class TestClass2 : ITest
{
public void Run()
{
Console.WriteLine("TestClass2");
}
}
public class TestClass4 : ITest
{
public void Run()
{
ITest t1 = new TestClass1();
t1.Run();
ITest t2 = new TestClass2();
t2.Run();
}
}
class Program
{
static void Main(string[] args)
{
const string ASSEMBLY_NAME = "MyDynamicAssembly";
AppDomain appDomain = AppDomain.CurrentDomain;
AssemblyName assemblyName = new AssemblyName(ASSEMBLY_NAME);
AssemblyBuilder assemblyBuilder = appDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndCollect);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, assemblyName.Name + ".dll");
TypeBuilder typeBuilder = moduleBuilder.DefineType("TestClass3", TypeAttributes.Public | TypeAttributes.Class);
typeBuilder.AddInterfaceImplementation(typeof(ITest));
MethodBuilder methodBuilder = typeBuilder.DefineMethod("Run", MethodAttributes.Public | MethodAttributes.Virtual);
ILGenerator iLGenerator = methodBuilder.GetILGenerator();
iLGenerator.DeclareLocal(typeof(ITest));
iLGenerator.Emit(OpCodes.Nop);
iLGenerator.Emit(OpCodes.Newobj, typeof(TestClass1).GetConstructors().First());
iLGenerator.Emit(OpCodes.Stloc_0);
iLGenerator.Emit(OpCodes.Ldloc_0);
iLGenerator.Emit(OpCodes.Callvirt, typeof(ITest).GetMethod("Run"));
iLGenerator.Emit(OpCodes.Nop);
iLGenerator.Emit(OpCodes.Nop);
iLGenerator.Emit(OpCodes.Newobj, typeof(TestClass2).GetConstructors().First());
iLGenerator.Emit(OpCodes.Stloc_0);
iLGenerator.Emit(OpCodes.Ldloc_0);
iLGenerator.Emit(OpCodes.Callvirt, typeof(ITest).GetMethod("Run"));
iLGenerator.Emit(OpCodes.Nop);
iLGenerator.Emit(OpCodes.Ret);
Type type = typeBuilder.CreateType();
ITest t = (ITest)Activator.CreateInstance(type);
t.Run();
Console.ReadLine();
}
}
本文版权归腿腿教学网及原创作者所有,未经授权,谢绝转载。