C# 数字枚举值作为字符串
我有以下枚举:
public enum Urgency {
VeryHigh = 1,
High = 2,
Routine = 4
}
我可以像这样获取枚举“值”作为字符串:
((int)Urgency.Routine).ToString() // returns "4"
注意:这不同于:
Urgency.Routine.ToString() // returns "Routine"
(int)Urgency.Routine // returns 4
有没有办法可以创建扩展类或静态实用程序类,这会提供一些语法糖吗? :)
I have the following enum:
public enum Urgency {
VeryHigh = 1,
High = 2,
Routine = 4
}
I can fetch an enum "value" as string like this:
((int)Urgency.Routine).ToString() // returns "4"
Note: This is different from:
Urgency.Routine.ToString() // returns "Routine"
(int)Urgency.Routine // returns 4
Is there a way I can create an extension class, or a static utliity class, that would provide some syntactical sugar? :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您应该能够使用 Enums ToString 方法的重载来为其提供格式字符串,这会将枚举的值打印为字符串。
You should just be able to use the overloads of Enums ToString method to give it a format string, this will print out the value of the enum as a string.
为了实现更多“人类可读”的枚举描述(例如,在您的示例中是“Very High”而不是“VeryHigh”),我用属性修饰了枚举值,如下所示:
然后,使用这样的扩展方法:
然后您可以称呼
in order to display your enum as more readable text.
In order to achieve more "human readable" descriptions for enums (e.g. "Very High" rather than "VeryHigh" in your example) I have decorated enum values with attribute as follows:
Then, used an extension method like this:
You can then just call
in order to display your enum as more readable text.
如果您只想处理此枚举,请使用 Mark Byer 的解决方案。
对于更通用的解决方案:
转换为十进制意味着您不需要显式处理 8 种不同的允许的基础整数类型,因为它们都无损转换为十进制,但彼此之间不进行无损转换(ulong 和 long 之间不会无损转换)彼此但都可以处理其余的所有事情)。这样做可能会更快(特别是如果您在比较顺序中选择得好),但会更加冗长,收益相对较小。
编辑:
虽然上面的内容不如弗兰肯托什的好,但弗兰肯托什看透了问题的真正问题,并非常雄辩地解决了它。
If you want to just deal with this enum, use Mark Byer's solution.
For a more general solution:
Converting to decimal means you don't need to deal with the 8 different allowed underlying integral types explicitly, as all of them convert losslessly to decimal but not to each other (ulong and long don't convert losslessly between each other but both can handle all the rest). Doing that would probably be faster (esp. if you pick well in your order of comparison), but a lot more verbose for relatively little gain.
Edit:
The above isn't as good as Frankentosh's though, Frankentosh saw through the question to the real problem and solves it very eloquently.
一个简单的方法
a simple approach
很棒的东西...我现在已经在我的项目中添加了一个扩展方法
现在我可以通过调用
Urgency.Routine.NumberString();
来获取 int 值 - 作为字符串 - 感谢 Frankentosh 和 Jon : )Great stuff ... I have now added an extension method to my project
Now I can get the int value - as a string - by calling
Urgency.Routine.NumberString();
Thanks to Frankentosh and Jon :)您可以为您的特定类型编写扩展方法:
使用如下:
You can write an extension method for your specific type:
Use as follows:
稍微反思一下怎么样?应该适用于所有底层类型。
然后:
How about a little reflection? Should work with all underlying types.
Then:
如果您愿意,您可以使扩展方法适用于所有枚举:
If you wanted, you could make the extension method work for all enums: