2 using System
.Threading
;
3 using System
.Reflection
;
4 using System
.Reflection
.Emit
;
7 [AttributeUsage (AttributeTargets
.All
)]
8 public class MyAttribute
: Attribute
{
9 public MyAttribute (object o
) {
23 public class MyConstructorBuilder
25 public static int Main()
27 Type myHelloworld
= MyCreateCallee(Thread
.GetDomain());
28 ConstructorInfo myConstructor
= myHelloworld
.GetConstructor(new Type
[]{typeof(String)}
);
29 object[] myAttributes1
= myConstructor
.GetCustomAttributes(true);
30 if (myAttributes1
== null)
32 if (myAttributes1
.Length
!= 1)
34 MyAttribute myAttribute
= myAttributes1
[0] as MyAttribute
;
35 if (myAttribute
== null)
37 if (myAttribute
.my
.GetType() != typeof(TypeCode
))
42 private static Type
MyCreateCallee(AppDomain domain
)
44 AssemblyName myAssemblyName
= new AssemblyName();
45 myAssemblyName
.Name
= "EmittedAssembly";
46 // Define a dynamic assembly in the current application domain.
47 AssemblyBuilder myAssembly
=
48 domain
.DefineDynamicAssembly(myAssemblyName
,AssemblyBuilderAccess
.Run
);
49 // Define a dynamic module in this assembly.
50 ModuleBuilder myModuleBuilder
= myAssembly
.DefineDynamicModule("EmittedModule");
51 // Construct a 'TypeBuilder' given the name and attributes.
52 TypeBuilder myTypeBuilder
= myModuleBuilder
.DefineType("HelloWorld",
53 TypeAttributes
.Public
);
54 // Define a constructor of the dynamic class.
55 ConstructorBuilder myConstructor
= myTypeBuilder
.DefineConstructor(
56 MethodAttributes
.Public
, CallingConventions
.Standard
, new Type
[]{typeof(String)}
);
57 ILGenerator myILGenerator
= myConstructor
.GetILGenerator();
58 myILGenerator
.Emit(OpCodes
.Ldstr
, "Constructor is invoked");
59 myILGenerator
.Emit(OpCodes
.Ldarg_1
);
60 MethodInfo myMethodInfo
=
61 typeof(Console
).GetMethod("WriteLine",new Type
[]{typeof(string)}
);
62 myILGenerator
.Emit(OpCodes
.Call
, myMethodInfo
);
63 myILGenerator
.Emit(OpCodes
.Ret
);
64 Type myType
= typeof(MyAttribute
);
65 ConstructorInfo myConstructorInfo
= myType
.GetConstructor(new Type
[]{typeof(object)}
);
68 CustomAttributeBuilder methodCABuilder
= new CustomAttributeBuilder (myConstructorInfo
, new object [] { TypeCode.Double }
);
70 myConstructor
.SetCustomAttribute(methodCABuilder
);
72 catch(ArgumentNullException ex
)
74 Console
.WriteLine("The following exception has occured : "+ex
.Message
);
78 Console
.WriteLine("The following exception has occured : "+ex
.Message
);
80 return myTypeBuilder
.CreateType();