.net core动态创建枚举

一、官方示例

官方示例非常简单,代码如下,也可以看看官方文档

AppDomain currentDomain = AppDomain.CurrentDomain;
AssemblyName aName = new AssemblyName("TempAssembly");
AssemblyBuilder ab = currentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder mb = ab.DefineDynamicModule(aName.Name, aName.Name + ".dll");
EnumBuilder eb = mb.DefineEnum("Elevation", TypeAttributes.Public, typeof(int));
eb.DefineLiteral("Low", 0);
eb.DefineLiteral("High", 1);
Type finished = eb.CreateType();
ab.Save(aName.Name + ".dll");
foreach( object o in Enum.GetValues(finished) )
{
    Console.WriteLine("{0}.{1} = {2}", finished, o, ((int) o));
}

二、兼容.net core、.net 5、.net 6

var currentDomain=AppDomain.CurrentDomain;
var assembly = Assembly.GetExecutingAssembly();
var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assembly!.GetName(), AssemblyBuilderAccess.Run);
var moduleBuilder = assemblyBuilder.DefineDynamicModule(assembly.GetName().Name!);
var em = moduleBuilder.DefineEnum("LoginType", TypeAttributes.Public, typeof(int));
em.DefineLiteral("Fail", 0);
em.DefineLiteral("Success", 1);
Type finished = em.CreateType()!;
foreach(object o in Enum.GetValues(finished))
{
    Console.WriteLine($"{finished}.{o} = {(int)o};");
}

补充下命名空间

using System.Reflection;
using System.Reflection.Emit;
posted @ 2022-04-25 17:00  shuisen  阅读(475)  评论(0编辑  收藏  举报