Use reflection to dynamically create Enum... Impossible?

Source: Internet
Author: User

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 );

}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.