2 using System
.Threading
;
3 using System
.Reflection
;
4 using System
.Reflection
.Emit
;
8 public static int Main (String
[] args
) {
9 AssemblyName assemblyName
= new AssemblyName ();
10 assemblyName
.Name
= "foo";
12 AssemblyBuilder assembly
=
13 Thread
.GetDomain ().DefineDynamicAssembly (
14 assemblyName
, AssemblyBuilderAccess
.RunAndSave
);
16 ModuleBuilder module
= assembly
.DefineDynamicModule ("foo.dll");
18 TypeBuilder if_tb
= module
.DefineType ("IF`1", TypeAttributes
.Public
|TypeAttributes
.Abstract
|TypeAttributes
.Interface
);
20 GenericTypeParameterBuilder
[] typeParams
= if_tb
.DefineGenericParameters ("T");
22 MethodBuilder if_mb
= if_tb
.DefineMethod ("foo", MethodAttributes
.Public
|MethodAttributes
.Abstract
|MethodAttributes
.Virtual
, typeParams
[0], Type
.EmptyTypes
);
23 MethodBuilder if_mb2
= if_tb
.DefineMethod ("foo2", MethodAttributes
.Public
|MethodAttributes
.Abstract
|MethodAttributes
.Virtual
, typeParams
[0], Type
.EmptyTypes
);
26 TypeBuilder tb
= module
.DefineType ("Foo`1", TypeAttributes
.Public
, typeof (object));
27 GenericTypeParameterBuilder
[] tbTypeParams
= tb
.DefineGenericParameters ("T");
30 Type inst
= if_tb
.MakeGenericType (tbTypeParams
[0]);
32 tb
.AddInterfaceImplementation (inst
);
34 var mb0
= tb
.DefineMethod ("foo", MethodAttributes
.Public
|MethodAttributes
.Virtual
, typeParams
[0], Type
.EmptyTypes
);
35 mb0
.GetILGenerator ().Emit (OpCodes
.Ret
);
37 var mb
= tb
.DefineMethod ("__foo", MethodAttributes
.Public
|MethodAttributes
.Virtual
, typeParams
[0],Type
.EmptyTypes
);
38 var gen
= mb
.GetILGenerator ();
39 var local
= gen
.DeclareLocal (typeParams
[0], false);
40 gen
.Emit (OpCodes
.Ldloca
, local
);
41 gen
.Emit (OpCodes
.Initobj
, typeParams
[0]);
42 gen
.Emit (OpCodes
.Ldloc
, local
);
43 gen
.Emit (OpCodes
.Ret
);
45 tb
.DefineMethodOverride (mb
, TypeBuilder
.GetMethod (inst
, if_mb
));
46 tb
.DefineMethodOverride (mb
, TypeBuilder
.GetMethod (inst
, if_mb2
));
48 var k
= if_tb
.CreateType ();
50 Type t
= tb
.CreateType ();
51 object obj
= Activator
.CreateInstance (t
.MakeGenericType (new Type
[] { typeof (string)}
));
52 var info
= k
.MakeGenericType (new Type
[] { typeof (string) }
).GetMethod ("foo");
53 var res
= info
.Invoke (obj
, null);
55 return res
== null ? 0 : 1;