我想在這裏實現的是有點棘手。在繼續之前,先讓我簡要介紹一下背景。使用動態枚舉作爲方法的參數類型
我知道我們可以使用枚舉作爲類型的方法的參數。例如,我可以做這樣的事情(一個非常簡單的例子)
namespace Test { class DefineEnums { public enum MyEnum { value1 = 0, value2 = 1 } } class UseEnums { public void UseDefinedEnums(DefineEnums.MyEnum _enum) { //Any code here. } public void Test() { // "value1" comes here with the intellisense. UseDefinedEnums(DefineEnums.MyEnum.value1); } } }
什麼,我需要做的是建立一個動態枚舉並用其作爲代替DefineEnums.MyEnum
類型如上所述。
我嘗試了以下。 1.使用我從網上獲得的方法從字符串列表創建一個動態枚舉。並創建了一個我可以使用的靜態類。
using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Test { public static class DynamicEnum { public static Enum finished; static List<string> _lst = new List<string>(); static DynamicEnum() { _lst.Add("value1"); _lst.Add("value2"); finished = CreateDynamicEnum(_lst); } public static Enum CreateDynamicEnum(List<string> _list) { // Get the current application domain for the current thread. AppDomain currentDomain = AppDomain.CurrentDomain; // Create a dynamic assembly in the current application domain, // and allow it to be executed and saved to disk. AssemblyName aName = new AssemblyName("TempAssembly"); AssemblyBuilder ab = currentDomain.DefineDynamicAssembly( aName, AssemblyBuilderAccess.RunAndSave); // Define a dynamic module in "TempAssembly" assembly. For a single- // module assembly, the module has the same name as the assembly. ModuleBuilder mb = ab.DefineDynamicModule(aName.Name, aName.Name + ".dll"); // Define a public enumeration with the name "Elevation" and an // underlying type of Integer. EnumBuilder eb = mb.DefineEnum("Elevation", TypeAttributes.Public, typeof(int)); // Define two members, "High" and "Low". //eb.DefineLiteral("Low", 0); //eb.DefineLiteral("High", 1); int i = 0; foreach (string item in _list) { eb.DefineLiteral(item, i); i++; } // Create the type and save the assembly. return (Enum)Activator.CreateInstance(eb.CreateType()); //ab.Save(aName.Name + ".dll"); } } }
- 使用類試過,但我無法找到上述定義的「成品」枚舉。即我不能做到以下幾點
public static void TestDynEnum(Test.DynamicEnum.finished _finished) { // Do anything here with _finished. }
我猜後已變得過於長,但我希望我已經說得很清楚。
還有一個類似的問題:http://stackoverflow.com/questions/725043/dynamic-enum-in-c – 2010-05-21 08:24:32