生成具有两个或多个动态枚举的DLL

本文关键字:动态 枚举 DLL 两个 | 更新日期: 2023-09-27 18:09:05

我遵循了这个Q &答:c#中的动态枚举,它工作得很好,最好的答案来自这篇msdn文章的代码:EnumBuilder类

此动态枚举代码生成适用于DLL中的一个枚举。问题是当我试图添加第二个枚举时,它不起作用,我只能从引用的DLL访问第一个枚举"海拔"。

如何在DLL中添加两个或多个枚举?

class Example
{
    public static void Main()
    {
        // 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);
        // Create the type and save the assembly.
        Type finished = eb.CreateType();
        //-------------------------------------
        //HERE IS THE CODE TO CREATE A 2ND ENUM
        //-------------------------------------
        EnumBuilder eb1 = mb.DefineEnum("SecondEnum", TypeAttributes.Public, typeof(int));
        eb1.DefineLiteral("Bad", 0);
        eb1.DefineLiteral("Good", 1);
        Type SecondEnum = eb1.CreateType();
        ab.Save(aName.Name + ".dll");
    }
}

生成具有两个或多个动态枚举的DLL

工作中发生了一些奇怪的事情,因为我可以在家里做。Ref tempassemassembly在另一个项目中,我可以访问SecondEnum:

using ProjectName;
...
private void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show(SecondEnum.Good.ToString());
}

更新:

原来我是在添加两个值(数字),而不是一个键和一个值。

SecondEnum.DefineLiteral("Must Be Alphanumeric", Convert.ToInt32(dr[0].ToString()));
更新2:

确保Enum不以空格开头!!