如何使用包含空格的枚举项名称?
enum Coolness
{
Not So Cool = 1,
VeryCool = 2,
Supercool = 3
}
Run Code Online (Sandbox Code Playgroud)
我通过下面的代码获取Enum项目名称
string enumText = ((Coolness)1).ToString()
Run Code Online (Sandbox Code Playgroud)
我不会改变这段代码,但上面的代码应该返回Not So Cool.有没有使用oops概念来实现这一目标?在这里,我不想更改检索语句.
使用显示属性:
enum Coolness : byte
{
[Display(Name = "Not So Cool")]
NotSoCool = 1,
VeryCool = 2,
Supercool = 3
}
Run Code Online (Sandbox Code Playgroud)
您可以使用此帮助程序来获取DisplayName
public static string GetDisplayValue(T value)
{
var fieldInfo = value.GetType().GetField(value.ToString());
var descriptionAttributes = fieldInfo.GetCustomAttributes(
typeof(DisplayAttribute), false) as DisplayAttribute[];
if (descriptionAttributes == null) return string.Empty;
return (descriptionAttributes.Length > 0) ? descriptionAttributes[0].Name : value.ToString();
}
Run Code Online (Sandbox Code Playgroud)
(感谢Hrvoje Stanisic为助手)