'Importing enum values from a file
I have an enum Tokens, which basically I use as codes for a logging system
public enum Tokens {
UnknownCommand = 100,
SoftwareVersion = 101
}
then I use a custom Logging that accepts a Token enum and a message:
Logger.LogError(Tokens.UnknownCommand, "SomeMessage")
This works well, however in a future my Tokens might have to change, so I was thinking that I could maybe import the token values from a Keys file.
However assigning new values to the Tokens doesn't seem to be a valid option.
Token.SoftwareVersion = 3;
Is there a way I can have an enum where the values can be imported from a file or changed?
Solution 1:[1]
You Can use Enum Builder.
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 ) );
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Amjad S. |
