代码之家  ›  专栏  ›  技术社区  ›  Sembei Norimaki

从文件导入枚举值

  •  0
  • Sembei Norimaki  · 技术社区  · 3 年前

    我有一个枚举令牌,基本上我用它作为日志系统的代码

    public enum Tokens {
        UnknownCommand = 100,
        SoftwareVersion = 101
    }
    

    然后我使用一个接受令牌枚举和消息的自定义日志:

    Logger.LogError(Tokens.UnknownCommand, "SomeMessage")
    

    这很有效,但是在将来我的令牌可能需要更改,所以我想我可能可以从密钥文件导入令牌值。

    然而,为令牌分配新值似乎不是一个有效的选项。

    Token.SoftwareVersion = 3;
    

    有没有一种方法可以让枚举从文件中导入或更改值?

    0 回复  |  直到 3 年前
        1
  •  0
  •   Amjad S.    3 年前

    可以使用枚举生成器。

     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("YOUR_ENUM_NAME", TypeAttributes.Public, typeof(int));
    
    
            // Read from file and then add to the enum members this way.
            // Define two members
            eb.DefineLiteral("UnknownCommand", 0);
            eb.DefineLiteral("SoftwareVersion", 1);
    
            // Create the type and save the assembly.
            Type finished = eb.CreateType();
            ab.Save(aName.Name + ".dll");
    
    
            // To retrieve Enum members use Enum.GetValues(YOUR_ENUM_NAME)
            foreach( object o in Enum.GetValues(YOUR_ENUM_NAME) )
            {
                Console.WriteLine("{0}.{1} = {2}", finished, o, ((int) o));
            }
           //OR 
    
          Array values = Enum.GetValues ( typeof ( YOUR_ENUM_NAME ) );
    
            foreach (var val in values)
            {
                Console.WriteLine ( String.Format ( "{0}: {1}",
                        Enum.GetName ( typeof ( YOUR_ENUM_NAME ), val ),
                        val ) );
            }
        }