Mercurial > pub > bltoolkit
comparison Examples/CS/Reflection.Emit/HelloWorldNormal.cs @ 0:f990fcb411a9
Копия текущей версии из github
author | cin |
---|---|
date | Thu, 27 Mar 2014 21:46:09 +0400 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:f990fcb411a9 |
---|---|
1 using System; | |
2 using System.Reflection; | |
3 using System.Reflection.Emit; | |
4 using System.Threading; | |
5 | |
6 using NUnit.Framework; | |
7 | |
8 namespace Examples.Reflection.Emit | |
9 { | |
10 [TestFixture] | |
11 public class HelloWorldNormal | |
12 { | |
13 public interface IHello | |
14 { | |
15 void SayHello(string toWhom); | |
16 } | |
17 | |
18 [Test] | |
19 public void Test() | |
20 { | |
21 AssemblyName asmName = new AssemblyName(); | |
22 | |
23 asmName.Name = "HelloWorld"; | |
24 | |
25 AssemblyBuilder asmBuilder = | |
26 Thread.GetDomain().DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave); | |
27 | |
28 ModuleBuilder modBuilder = asmBuilder.DefineDynamicModule("HelloWorld"); | |
29 | |
30 TypeBuilder typeBuilder = modBuilder.DefineType( | |
31 "Hello", | |
32 TypeAttributes.Public, | |
33 typeof(object), | |
34 new Type[] { typeof(IHello) }); | |
35 | |
36 MethodBuilder methodBuilder = typeBuilder.DefineMethod("SayHello", | |
37 MethodAttributes.Private | MethodAttributes.Virtual, | |
38 typeof(void), | |
39 new Type[] { typeof(string) }); | |
40 | |
41 typeBuilder.DefineMethodOverride(methodBuilder, typeof(IHello).GetMethod("SayHello")); | |
42 | |
43 ILGenerator il = methodBuilder.GetILGenerator(); | |
44 | |
45 // string.Format("Hello, {0} World!", toWhom) | |
46 // | |
47 /*[a]*/il.Emit/*[/a]*/(OpCodes.Ldstr, "Hello, {0} World!"); | |
48 /*[a]*/il.Emit/*[/a]*/(OpCodes.Ldarg_1); | |
49 /*[a]*/il.Emit/*[/a]*/(OpCodes.Call, typeof(string).GetMethod("Format", new Type[] { typeof(string), typeof(object) })); | |
50 | |
51 // Console.WriteLine("Hello, World!"); | |
52 // | |
53 /*[a]*/il.Emit/*[/a]*/(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) })); | |
54 /*[a]*/il.Emit/*[/a]*/(OpCodes.Ret); | |
55 | |
56 Type type = typeBuilder.CreateType(); | |
57 | |
58 IHello hello = (IHello)Activator.CreateInstance(type); | |
59 | |
60 hello.SayHello("Emit"); | |
61 } | |
62 } | |
63 } |