gpt4 book ai didi

c# - 动态生成时自定义 C# Enum ToString()

转载 作者:太空宇宙 更新时间:2023-11-03 17:44:36 29 4
gpt4 key购买 nike

我在 C# ASP.NET 解决方案中生成代表我的数据库中的整数 ID 的动态枚举。我想要两件事,尽管两者都不可能。

1) 例如,我希望 .ToString() 方法给我“345”,而不是枚举的字符串名称(它表示为字符串的 int)。这个问题的每一个答案似乎都在添加

[Description="Blah"]
EnumName = 1

在声明之上并使用 GetDescription() 方法。我不知道如何使用我正在使用的动态代码执行此操作。

2) 我宁愿不转换为 int 来使用它,例如,我宁愿 (Enum.Name == 5)。如果这不可能,我会强制转换,但我真的不想使用 ((int)Enum.Name)).ToString();

这是动态代码生成:

public static void Main()
{
AppDomain domain = AppDomain.CurrentDomain;

AssemblyName aName = new AssemblyName("DynamicEnums");
AssemblyBuilder ab = domain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Save);

ModuleBuilder mb = ab.DefineDynamicModule(aName.Name, aName.Name + ".dll");

List<Type> types = new List<Type>();

foreach(ReferenceType rt in GetTypes())
{
EnumBuilder eb = mb.DefineEnum(rt.Name, TypeAttributes.Public, typeof(int));

foreach (Reference r in GetReferences(rt.ID))
{
eb.DefineLiteral(NameFix(r.Name), r.ID);
}

types.Add(eb.CreateType());
}

ab.Save(aName.Name + ".dll");

foreach (Type t in types)
{
foreach (object o in Enum.GetValues(t))
{
Console.WriteLine("{0}.{1} = {2}", t, o, ((int) o));
}

Console.WriteLine();
//Console.ReadKey();
}

Console.WriteLine();
Console.WriteLine("Dynamic Enums Built Successfully.");
}

public static string NameFix(string name)
{
//Strip all non alphanumeric characters
string r = Regex.Replace(name, @"[^\w]", "");

//Enums cannot begin with a number
if (Regex.IsMatch(r, @"^\d"))
r = "N" + r;

return r;
}

可能只是没有办法做我想做的事,我会被困在使用:

(int)Countries.USA //For int value
((int)Countries.CAN).ToString() //For string representation of int value, ex. "354"

有什么想法吗?

最佳答案

您能否调整类型安全的枚举模式来满足您的需求?

public class MyEnum
{
#region Enum Values

// Pre defined values.
public static readonly MyEnum ValueOne = new MyEnum(0);
public static readonly MyEnum ValueTwo = new MyEnum(1);

// All values in existence.
private static readonly Dictionary<int, MyEnum> existingEnums = new Dictionary<int, MyEnum>{{ValueOne.Value, ValueOne}, {ValueTwo.Value, ValueTwo}};

#endregion

#region Enum Functionality

private readonly int Value;

private MyEnum(int value)
{
Value = value;
}

public static MyEnum GetEnum(int value)
{
// You will probably want to make this thread-safe.
if (!existingEnums.ContainsKey(value)) existingEnums[value] = new MyEnum(value);

return existingEnums[value];
}

public override string ToString()
{
return Value.ToString();
}

#endregion
}

用法:

private void Foo(MyEnum enumVal)
{
return "Enum Value: " + enumVal; // returns "Enum Value: (integer here)
}

或者:

MyEnum.GetValue(2) == MyEnum.GetValue(4); // false
MyEnum.GetValue(3) == MyEnum.GetValue(3); // true

关于c# - 动态生成时自定义 C# Enum ToString(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7764332/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com