gpt4 book ai didi

c# - C# 枚举中具有相同整数值的元素的排序

转载 作者:行者123 更新时间:2023-11-30 19:44:54 25 4
gpt4 key购买 nike

我有一个简单的枚举:

enum E
{
FullNameForA = 1,
A = 1,
FullNameForB = 2,
B = 2
}

目标是能够对相同的整数值使用不同的字符串值,但必须使用 FullNameFor* 作为默认值。换句话说,用户可以提供 E.A 作为输入,但代码应使用 E.FullNameForA 作为输出。

似乎默认情况下,C# 将使用具有相同整数值的元素的字母顺序排序,这使我的目标更加困难。是对的吗?有什么办法可以克服这个问题吗?

最佳答案

It seems like by default C# will use alphabetical ordering of elements with the same integral value

在什么情况下?当您将值转换回字符串时?来自 Enum.ToString 的文档:

If multiple enumeration members have the same underlying value and you attempt to retrieve the string representation of an enumeration member's name based on its underlying value, your code should not make any assumptions about which name the method will return.

(请注意,决定在 BCL 中 - 它不是语言决定。)

我建议,如果您希望每个值都有一个规范 字符串表示,您可以创建一个Dictionary<E, string>。并咨询而不是打电话ToString() .

关于c# - C# 枚举中具有相同整数值的元素的排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11637532/

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