I've been tasked to generate a dynamic enumeration that has database driven values to alleviate recompiling and deployment of the Enum object when new values are added. The enumeration will exist as part of a internally consumed service.
The natural and most obvious advantage of this approach I suppose would be that anyone having need to consume the service would know immediately what values are available during development.
I'm not a big fan of this approach but I am up for the challenge.
The following code produces a RuntimeType but it throws an error on every attempt I've made in effort to cast this as an Enum.
public Enum GenerateDynamicSmsEnumValues<T>(Dictionary<int,string> enumValues)
{
try
{
// Create Base Assembly Objects
AppDomain appDomain = AppDomain.CurrentDomain;
AssemblyName asmName = new AssemblyName("SmsApplicationID");
AssemblyBuilder asmBuilder = appDomain.
DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);
// Create Module and Enumeration Builder Objects
ModuleBuilder modBuilder = asmBuilder.
DefineDynamicModule("SmsApplicationID");
EnumBuilder enumBuilder = modBuilder.
DefineEnum("SmsApplicationID", TypeAttributes.Public, typeof(int));
// Build enumerations
foreach (var pair in enumValues)
enumBuilder.DefineLiteral(pair.Value, pair.Key);
var returnType = enumBuilder.CreateType();
var enm = (object)returnType;
return (Enum)enm; // <-- Error Thrown Here
}
catch(Exception ex)
{
return null;
}
If I inspect the object before the attempted cast the IsEnum attribute is set to true so I believe I have the object I need.
I just cannot figure out how to properly cast it to an Enum type to be used by any code leveraging the method.
I have also tried this approach using a Generic Template method but the problem is pretty much the same.
How can I cast this to an Enum object???
Aucun commentaire:
Enregistrer un commentaire