生成内部类用TypeBuilder的DefineNestedType方法,得到另一个TypeBuilder。
内部类的可访问性都是TypeAttributes的“Nested”开头一些成员。
实例代码:
ypeBuilder nestedBuilder = typeBuilder.DefineNestedType("NestedClass", TypeAttributes.NestedPublic | TypeAttributes.Sealed);
完整程序如下:
using System; using System.Reflection; using System.Reflection.Emit; namespace LX1_ILDemo { class Demo27_NestedType { static string binaryName = "Demo27_NestedType.dll"; static string namespaceName = "LX1_ILDemo"; static string typeName = "DemoNestedType"; static AssemblyBuilder assemblyBuilder; static ModuleBuilder moduleBuilder; static TypeBuilder typeBuilder; static void Emit_NestedMethod() { TypeBuilder nestedBuilder = typeBuilder.DefineNestedType("NestedClass", TypeAttributes.NestedPublic | TypeAttributes.Sealed); var testMethod = nestedBuilder.DefineMethod("Hello", MethodAttributes.Public | MethodAttributes.Static, typeof(void), new Type[] { }); ILGenerator ilGenerator = testMethod.GetILGenerator(); ilGenerator.EmitWriteLine("hello"); ilGenerator.Emit(OpCodes.Ret); Type nestedType = nestedBuilder.CreateType(); } public static void Generate() { InitAssembly(); typeBuilder = moduleBuilder.DefineType(namespaceName + "." + typeName, TypeAttributes.Public); Emit_NestedMethod(); GenerateMain(); SaveAssembly(); Console.WriteLine("生成成功"); } static void GenerateMain() { var mainMethod = typeBuilder.DefineMethod("Test", MethodAttributes.Public | MethodAttributes.Static, typeof(void), new Type[] { }); var ilGenerator = mainMethod.GetILGenerator(); ilGenerator.EmitWriteLine("Test"); ilGenerator.Emit(OpCodes.Ret); } static void InitAssembly() { AssemblyName assemblyName = new AssemblyName(namespaceName); assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave); moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, binaryName); } static void SaveAssembly() { Type t = typeBuilder.CreateType(); //完成Type,这是必须的 assemblyBuilder.Save(binaryName); } } }