AssemblyBuilder assembly = curAppDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save);

 // Поскольку создается одномодульный компоновочный блок,

 // имя модуля будет совпадать с именем компоновочного блока.

 ModuleBuilder module = assembly.DefineDynamicModule("MyAssembly", "MyAssemblу.dll");

 // Определение открытого класса с именем "HelloWorld".

 TypeBuilder helloWorldClass = module.DefineType("MyAssembly.HelloWorld", TypeAttributes.Public);

 // Определение приватной переменной String с именем "theMessage".

 FieldBuilder msgField = helloWorldClass.DefineField("theMessage", Type.GetType("System.String"), FieldAttributes.Private);

 // Создание пользовательского конструктора.

 Type[] constructorArgs = new Type[1];

 constructorArgs[0] = typeof(string);

 ConstructorBuilder constructor = helloWorldClass.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, constructorArgs);

 ILGenerator constructorIL = constructor.GetILGenerator;

 constructorIL.Emit(OpCodes.Ldarg_0);

 Type objectClass = typeof(object);

 ConstructorInfo superConstructor = objectClass.GetConstructor(new Type[0]);

 constructorIL.Emit(OpCodes.Call, superConstructor);

 constructorIL.Emit(Opcodes.Ldarg_0);

 constructorIL.Emit(Opcodes.Ldarg_1);

 constructorIL.Emit(OpCodes.Stfld, msgField);

 constructorIL.Emit(OpCodes.Ret);

 // Создание конструктора, заданного по умолчанию.

 helloWorldClass.DefineDefaultConstructor(MethodAttributes.Public);

 // Теперь создание метода GetMsg.

 MethodBuilder getMsgMethod = helloWorldClass.DefineMethod("GetMsg", MethodAttributes.Public, typeof(string), null);

 ILGenerator methodIL = getMsgMethod.GetILGenerator;

 methodIL.Emit(OpCodes.Ldarg_0);

 methodIL.Emit(OpCodes.Ldfld, msgField);

 methodIL.Emit(Opcodes.Ret);

 // Создание метода SayHello.

 MethodBuilder sayHiMethod = helloWorldClass.DefineMethod("SayHello", MethodAttributes.Public, null, null);

 methodIL = sayHiMethod.GetILGenerator;

 methodIL.EmitWriteLine("Привет от класса HelloWorld!");

 methodIL.Emit(Opcodes.Ret);

 // Генерирование класса HelloWorld.

 helloWorldClass.CreateType;

 // (Необязательно.) Сохранение компоновочного блока в файл.

 assembly.Save("MyAssembly.dll");

}

<p>Генерирование компоновочного блока и набора модулей</p>

Метод начинается с указания минимального набора характеристик компоновочного блока, для чего используются типы AssemblyName и Version (определенные в пространстве имен System.Reflection). Затем с помощью метода уровня экземпляра AppDomain.DеfineDynamicAssembly вы получаете тип AssemblyBuilder (напомним, что вызывающая сторона передаст в метод CreateMyAsm ссылку на AppDomain).

// Установка общих характеристик компоновочного блока

// и получение доступа к типу AssemblyBuilder.

Перейти на страницу:

Похожие книги