using System using System Reflection using System Reflection Emit name

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System;
using System.Reflection;
using System.Reflection.Emit;
namespace DynHelloWorld
{
class Programmer
{
static public Type WriteCode()
{
AssemblyName assemblyName = new AssemblyName();
assemblyName.Name = "HelloWorldAssembly";
AssemblyBuilder assemblyBuilder =
AppDomain.CurrentDomain.DefineDynamicAssembly(
assemblyName, AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder =
assemblyBuilder.DefineDynamicModule("HelloWorldModule");
TypeBuilder typeBuilder =
moduleBuilder.DefineType("HelloWorldClass"
, TypeAttributes.Public);
MethodBuilder methodBuilder =
typeBuilder.DefineMethod("HelloWorld"
, MethodAttributes.Public
, null, null);
ILGenerator il = methodBuilder.GetILGenerator();
// Генерируем код.
il.EmitWriteLine("Hello World!");
il.Emit(OpCodes.Ret);
return typeBuilder.CreateType();
}
}
class Class1
{
static void Main()
{
Type typeCode = Programmer.WriteCode();
object objCode = Activator.CreateInstance(typeCode);
MethodInfo methodInfo = typeCode.GetMethod("HelloWorld");
methodInfo.Invoke(objCode, null);
Console.ReadLine();
}
}
}