枚举的字符串表示(estring)?
我需要一个枚举或类似的东西来做这样的事情:
公共枚举MyStringEnum { [StringValue("Foo A")] Foo = "A", [StringValue("Foo B")] Foo = "B" }
这可能吗?我的示例,我返回一个数据集,其值表示为 A、B、C、D、E .. 我需要一个解决方案将其返回为字符串表示形式?
我想显而易见的是创建一个扩展方法或只有一个 switch 语句并返回一个字符串的东西..还有其他更干净的解决方案吗?
问候, 戴夫
i need an enum or something similiar to do something like this:
public enum MyStringEnum {
[StringValue("Foo A")] Foo = "A",
[StringValue("Foo B")] Foo = "B" }
is this possible? my example, i return back a dataset with a value represented as either A,B,C,D,E .. i need a solution to return this as a string representation?
i guess the obvious would be to create an extension method or something which just had a switch statement in and return a string .. any other cleaner solutions?
regards,
dave
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是我们 MVC 应用程序用来检索枚举的显示名称的东西。它使用自定义属性和扩展方法来检索枚举显示名称。
枚举的用法:
获取显示名称:
Here is something we use for our MVC applications to retrieve a display name for our enums. It uses a custom attribute and an extension method to retrieve the enum display name.
Usage on the enum:
Getting back the display name:
是否可以选择不使用枚举而使用结构?
然后,您可以像使用带有自己的 ToString() 重载的枚举一样使用 FooEnum:
Would it be an option not to use enum and use structs instead?
You could then use FooEnum like an enum with an own ToString() overload:
如果你想做这样的事情:
像这样设置你的枚举:
并使用读取属性的实用程序/扩展方法:
If you want to do something like this:
Setup your enum like this:
And use a utility/extension method that reads the attribute:
我已经在我要放置的地方看到了这种情况
在这种情况下它会给出“A”
I've seen this done where I would put
In this case it would give "A"
解决此问题的最干净的解决方案是创建一个自定义属性,该属性将存储您想要的枚举常量的字符串值。我过去曾使用过该策略,效果相当好。这是一篇详细介绍所涉及工作的博客文章:
C# 中带有字符串值的枚举 - Stefan Sedich 的博客
当然,仅当您需要某种有意义的文本时才需要这样做。如果枚举常量的名称适合您...那么您只需调用
ToString()
即可。The cleanest solution for this problem is to create a custom attribute that will store the string value you want for the enum constant. I've used that strategy in the past and it worked out fairly well. Here's a blog post detailing the work involved:
Enum With String Values In C# - Stefan Sedich's Blog
Of course this is only necessary if you need some kind of meaningful text. If the name of the enum constant works for you...then you can simply call
ToString()
.