如何在 C# 中获取枚举的小写表示形式?
我在 ASP.NET MVC 应用程序中有以下enum
,并且我想使用该枚举作为参数。为此,我想返回该枚举的小写字符串表示形式。
public enum SortOrder
{
Newest = 0,
Rating = 1,
Relevance = 2
}
如何在 C# 中获取枚举的小写表示形式?我希望枚举也保留其自然的标题表示形式。
I have the following enum
in an ASP.NET MVC application, and I want to use that enum as a parameter. To do so, I'd like to to return the lowercase string representation of that enum
.
public enum SortOrder
{
Newest = 0,
Rating = 1,
Relevance = 2
}
How can I get the lowercase representation of an enum in C#? I'd like for the enums to retain their natural titlecase representation as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,除了
object
上的扩展方法之外,没有其他方法。No, there isn't except for an extension method on
object
.否(除非您更改枚举:
最新
、评级
、相关性
...)常见技术是针对每个枚举成员添加属性,指定要与其关联的字符串,例如:
http ://weblogs.asp.net/grantbarrington/archive/2009/01/19/enumhelper-getting-a-friend-description-from-an-enum.aspx
No (unless you change the enum:
newest
,rating
,relevance
...)A common technique is to add an attribute against each enum member, specifying the string that you want to associate with it, For instance:
http://weblogs.asp.net/grantbarrington/archive/2009/01/19/enumhelper-getting-a-friendly-description-from-an-enum.aspx
如果显示枚举文本的内容知道(并利用)System.ComponentModel 命名空间,那么您可以使用 System.ComponentModel.DescriptionAttribute 装饰枚举,并自行键入小写版本。
如果您直接获取字符串值,您仍然可以这样做,尽管编写反射代码的开销可能超出您想要处理的开销。
哈特哈,
布莱恩
If what is displaying the enum text is aware of (and utilizes) the System.ComponentModel namespace, then you can decorate the enum with the System.ComponentModel.DescriptionAttribute and type the lowercase version in yourself.
If you are directly getting the string value, you can still do this, though the overhead of you writing the reflection code may be more than you want to deal with.
HTH,
Brian
您还可以使用 Enum.GetNames(...) 来获取包含枚举值的字符串数组。然后,将它们转换为小写。要将字符串转换为相应的枚举值,您可以使用
Enum.Parse
方法在第三个参数中传递true
,这使得比较时不区分大小写。You might also use
Enum.GetNames(...)
to get a string array containing the enum values. Then, convert these to lower case. To convert from string to the respective enum value you can use theEnum.Parse
method passingtrue
in the third parameter, which makes the comparison case insensitive.