简体   繁体   English

如何在C#中获取枚举的小写表示?

[英]How do I get the lowercase representation of an enum in C#?

I have the following enum in an ASP.NET MVC application, and I want to use that enum as a parameter. 我在ASP.NET MVC应用程序中有以下enum ,我想将该枚举用作参数。 To do so, I'd like to to return the lowercase string representation of that enum . 为此,我想返回该enum的小写字符串表示形式。

 public enum SortOrder
 {
      Newest = 0,
      Rating = 1, 
      Relevance = 2 
 }

How can I get the lowercase representation of an enum in C#? 如何在C#中获取枚举的小写表示? I'd like for the enums to retain their natural titlecase representation as well. 我想让enums保留他们的天然标题表示。

No, there isn't except for an extension method on object . 不,除了object的扩展方法之外没有。

public static string ToLower (this object obj)
{
  return obj.ToString().ToLower();
}

Is there any way to get the string in lower case exceptiong: value.ToString().ToLower() ? 有没有办法得到小写例外的字符串例外:value.ToString()。ToLower()?

No (unless you change the enum: newest , rating , relevance ...) 否(除非您更改枚举: newestratingrelevance ......)

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 一种常见的技术是为每个枚举成员添加一个属性,指定要与其关联的字符串,例如: http//weblogs.asp.net/grantbarrington/archive/2009/01/19/enumhelper-getting -a友好,说明从-的- enum.aspx

You might also use Enum.GetNames(...) to get a string array containing the enum values. 您也可以使用Enum.GetNames(...)来获取包含枚举值的字符串数组。 Then, convert these to lower case. 然后,将这些转换为小写。 To convert from string to the respective enum value you can use the Enum.Parse method passing true in the third parameter, which makes the comparison case insensitive. 要从字符串转换为相应的枚举值,您可以使用Enum.Parse方法在第三个参数中传递true ,这使得比较不区分大小写。

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. 如果显示枚举文本的内容知道(并利用)System.ComponentModel命名空间,那么您可以使用System.ComponentModel.DescriptionAttribute修饰枚举,并在自己中键入小写版本。

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 HTH,Brian

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM