有谁知道如何将枚举值转换为人类可读的值?
例如:
ThisIsValueA应为"This is Value A".
Leon Bambric.. 17
从某个Ian Horwill 很久以前留在博客文章中的vb代码片段中转换出来...我已经成功地在生产中使用了它.
////// Add spaces to separate the capitalized words in the string, /// i.e. insert a space before each uppercase letter that is /// either preceded by a lowercase letter or followed by a /// lowercase letter (but not for the first char in string). /// This keeps groups of uppercase letters - e.g. acronyms - together. /// /// A string in PascalCase ///public static string Wordify(string pascalCaseString) { Regex r = new Regex("(?<=[a-z])(? [A-Z])|(?<=.)(? [A-Z])(?=[a-z])"); return r.Replace(pascalCaseString, " ${x}"); }
(要求'使用System.Text.RegularExpressions;')
从而:
Console.WriteLine(Wordify(ThisIsValueA.ToString()));
会回来,
"This Is Value A".
它比提供描述属性更简单,更少冗余.
只有当您需要提供一个间接层(问题没有要求)时,属性才有用.
从某个Ian Horwill 很久以前留在博客文章中的vb代码片段中转换出来...我已经成功地在生产中使用了它.
////// Add spaces to separate the capitalized words in the string, /// i.e. insert a space before each uppercase letter that is /// either preceded by a lowercase letter or followed by a /// lowercase letter (but not for the first char in string). /// This keeps groups of uppercase letters - e.g. acronyms - together. /// /// A string in PascalCase ///public static string Wordify(string pascalCaseString) { Regex r = new Regex("(?<=[a-z])(? [A-Z])|(?<=.)(? [A-Z])(?=[a-z])"); return r.Replace(pascalCaseString, " ${x}"); }
(要求'使用System.Text.RegularExpressions;')
从而:
Console.WriteLine(Wordify(ThisIsValueA.ToString()));
会回来,
"This Is Value A".
它比提供描述属性更简单,更少冗余.
只有当您需要提供一个间接层(问题没有要求)时,属性才有用.
Enums上的.ToString在C#中相对较慢,与GetType().Name(它甚至可能在封面下使用它)相比.
如果您的解决方案需要非常快速或高效,那么最好将您的转换缓存在静态字典中,并从那里查找它们.
@ Leon的代码的小改编,以利用C#3.这作为枚举的扩展是有意义的 - 如果你不想让所有这些都混乱,你可以将它限制为特定的类型.
public static string Wordify(this Enum input) { Regex r = new Regex("(?<=[a-z])(?[A-Z])|(?<=.)(? [A-Z])(?=[a-z])"); return r.Replace( input.ToString() , " ${x}"); } //then your calling syntax is down to: MyEnum.ThisIsA.Wordify();