comparison UnitTests/CS/Reflection/Emit/MethodBuilderHelperTest.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
4 using NUnit.Framework;
5
6 using BLToolkit.Reflection.Emit;
7
8 namespace Reflection.Emit
9 {
10 [TestFixture]
11 public class MethodBuilderHelperTest
12 {
13 public abstract class TestObject
14 {
15 public abstract int Property { get; }
16 protected abstract int Method1(float f);
17 public abstract int Method2(float f);
18
19 public int Method3(float f) { return Method1(f); }
20 }
21
22 [Test]
23 public void Test()
24 {
25 TypeBuilderHelper typeBuilder =
26 new AssemblyBuilderHelper("HelloWorld.dll").DefineType("Test", typeof(TestObject));
27
28 // Property
29 //
30 PropertyInfo propertyInfo = typeof(TestObject).GetProperty("Property");
31 MethodBuilderHelper methodBuilder = typeBuilder.DefineMethod(propertyInfo.GetGetMethod());
32 EmitHelper emit = methodBuilder.Emitter;
33
34 emit
35 .ldc_i4(10)
36 .ret()
37 ;
38
39 // Method1
40 //
41 MethodInfo methodInfo = typeof(TestObject).GetMethod(
42 "Method1", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
43
44 methodBuilder = typeBuilder.DefineMethod(methodInfo);
45 emit = methodBuilder.Emitter;
46
47 emit
48 .ldc_i4(10)
49 .ret()
50 ;
51
52 // Method2
53 //
54 methodInfo = typeof(TestObject).GetMethod("Method2", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
55
56 methodBuilder = typeBuilder.DefineMethod(
57 "Method2",
58 MethodAttributes.Virtual |
59 MethodAttributes.Public |
60 MethodAttributes.HideBySig |
61 MethodAttributes.PrivateScope |
62 MethodAttributes.VtableLayoutMask,
63 typeof(int),
64 new Type[] { typeof(float) });
65
66 typeBuilder.TypeBuilder.DefineMethodOverride(methodBuilder, methodInfo);
67
68 emit = methodBuilder.Emitter;
69
70 emit
71 .ldc_i4(10)
72 .ret()
73 ;
74
75 // Create type.
76 //
77 Type type = typeBuilder.Create();
78
79 TestObject obj = (TestObject)Activator.CreateInstance(type);
80
81 Assert.AreEqual(10, obj.Property);
82 Assert.AreEqual(10, obj.Method3(0));
83 Assert.AreEqual(10, obj.Method2(0));
84 }
85 }
86 }