A friend has a problem. To dynamically create enumerations, it is basically impossible to google it.CodeAfter testing, it seems impossible. The key lies inProgramDuring running, you can find that an enumeration has been created, but there is no way to use it, that is, there is no way to instantiate it.
The following is my test code. If you are interested, run.
Using system;
Using system. Threading;
Using system. reflection;
Using system. reflection. emit;
Namespace enumtest1
{
Enum Test
{
A,
B,
C
}
/// <Summary>
/// Summary description for class1.
/// </Summary>
Class class1
{
Static void test ()
{
Assembly ass = assembly. Load ("dymaicenum ");
// Using debug mode, watch Ty, it's type is enumtest1.test. only has one value
// Also in debug mode, watch enumtest1.test, it's turely A Enum, type is int.
Enum ty = (Enum) ass. createinstance ("enumtest1.test ");
}
/// <Summary>
/// The main entry point for the application.
/// </Summary>
[Stathread]
Static void main (string [] ARGs)
{
Test ();
Appdomain domain = thread. getdomain ();
Assemblyname name = new assemblyname ();
Name. Name = "enumassembly ";
Assemblybuilder asmbuilder = domain. definedynamicassembly (
Name, assemblybuilderaccess. Run );
Modulebuilder modbuilder =
Asmbuilder. definedynamicmodule ("enummodule ");
Enumbuilder = modbuilder. defineenum ("language ",
Typeattributes. Public,
Typeof (system. int32 ));
String [] Al = {"En-uk", "Ar-sa", "Da-DK", "French", "cantonese "};
For (INT I = 0; I <Al. length; I ++)
{
// Here Al is an array list with a list of string values
Enumbuilder. defineliteral (Al [I]. tostring (), I );
}
Type enumtype = enumbuilder. createtype ();
// Using debug mode, watch Ty, it's type is language. only has one value "En-uk"
// Also in debug mode, watch "language", it's an existent Enum, type is int.
Enum enumobj = (Enum) activator. createinstance (enumtype );
}
}
}