在C#中使用Emit動態創建類,需要使用System.Reflection.Emit命名空間中的類和方法。以下是一個簡單的示例,演示了如何使用Emit動態創建一個簡單的類:
using System;
using System.Reflection;
using System.Reflection.Emit;
public class DynamicClassCreator
{
public static Type CreateDynamicClass()
{
// 創建一個AssemblyBuilder
AssemblyName assemblyName = new AssemblyName("DynamicAssembly");
AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
// 創建一個ModuleBuilder
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("DynamicModule");
// 創建一個TypeBuilder
TypeBuilder typeBuilder = moduleBuilder.DefineType("DynamicClass", TypeAttributes.Public);
// 添加一個字段
FieldBuilder fieldBuilder = typeBuilder.DefineField("dynamicField", typeof(string), FieldAttributes.Private);
// 添加一個構造函數
ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(string) });
ILGenerator constructorIL = constructorBuilder.GetILGenerator();
constructorIL.Emit(OpCodes.Ldarg_0);
constructorIL.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes));
constructorIL.Emit(OpCodes.Ldarg_0);
constructorIL.Emit(OpCodes.Ldarg_1);
constructorIL.Emit(OpCodes.Stfld, fieldBuilder);
constructorIL.Emit(OpCodes.Ret);
// 創建類型
Type dynamicType = typeBuilder.CreateType();
return dynamicType;
}
}
public class Program
{
public static void Main()
{
Type dynamicType = DynamicClassCreator.CreateDynamicClass();
// 創建一個實例
object dynamicInstance = Activator.CreateInstance(dynamicType, "Hello, Emit!");
// 調用字段值
FieldInfo fieldInfo = dynamicType.GetField("dynamicField", BindingFlags.NonPublic | BindingFlags.Instance);
string fieldValue = (string)fieldInfo.GetValue(dynamicInstance);
Console.WriteLine(fieldValue);
}
}
在上面的示例中,我們首先創建了一個AssemblyBuilder、ModuleBuilder和TypeBuilder,然后分別定義了一個字段和一個構造函數。最后,我們使用CreateType方法創建了動態類,并通過Activator.CreateInstance方法創建了一個動態類的實例。最后,我們通過反射獲取字段的值并打印輸出。