将枚举转换为人类可读的值

Jed*_*oky 25 c# enums human-readable

有谁知道如何将枚举值转换为人类可读的值?

例如:

ThisIsValueA应为"This is Value A".

Leo*_*ick 17

从某个Ian Horwill 很久以前留在博客文章中的vb代码片段中转换出来...我已经成功地在生产中使用了它.

    /// <summary>
    /// 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.
    /// </summary>
    /// <param name="pascalCaseString">A string in PascalCase</param>
    /// <returns></returns>
    public static string Wordify(string pascalCaseString)
    {            
        Regex r = new Regex("(?<=[a-z])(?<x>[A-Z])|(?<=.)(?<x>[A-Z])(?=[a-z])");
        return r.Replace(pascalCaseString, " ${x}");
    }
Run Code Online (Sandbox Code Playgroud)

(要求'使用System.Text.RegularExpressions;')

从而:

Console.WriteLine(Wordify(ThisIsValueA.ToString()));
Run Code Online (Sandbox Code Playgroud)

会回来,

"This Is Value A".
Run Code Online (Sandbox Code Playgroud)

它比提供描述属性更简单,更少冗余.

只有当您需要提供一个间接层(问题没有要求)时,属性才有用.


Kei*_*ith 11

Enums上的.ToString在C#中相对较慢,与GetType().Name(它甚至可能在封面下使用它)相比.

如果您的解决方案需要非常快速或高效,那么最好将您的转换缓存在静态字典中,并从那里查找它们.


@ Leon的代码的小改编,以利用C#3.这作为枚举的扩展是有意义的 - 如果你不想让所有这些都混乱,你可以将它限制为特定的类型.

public static string Wordify(this Enum input)
{            
    Regex r = new Regex("(?<=[a-z])(?<x>[A-Z])|(?<=.)(?<x>[A-Z])(?=[a-z])");
    return r.Replace( input.ToString() , " ${x}");
}

//then your calling syntax is down to:
MyEnum.ThisIsA.Wordify();
Run Code Online (Sandbox Code Playgroud)


Mat*_*ton 5

我见过的大多数示例都涉及使用 [Description] 属性标记枚举值,并使用反射在值和描述之间进行“转换”。这是一篇关于它的旧博客文章:

<链接>