使用反射动态创建Enum...不可能?
朋友有个难题,要动态创建枚举,google了一下,基本都是不可能.自己写了个代码测试了一下,貌似确实不可能.关键就在于,在程序运行的时候可以发现已经创造出了一个枚举,但是没有办法使用,即没有办法实例化.
下面是我的测试代码,有兴趣的放vs上跑跑,呵呵
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 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);
}
}
}