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

例如:

ThisIsValueA 应该是“这是值 A”。

有帮助吗?

解决方案

将其从某个 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}");
    }

(需要,“使用 System.Text.RegularExpressions;”)

因此:

Console.WriteLine(Wordify(ThisIsValueA.ToString()));

会回来,

"This Is Value A".

它比提供描述属性要简单得多,而且冗余更少。

仅当您需要提供间接层(问题没有要求)时,属性在这里才有用。

其他提示

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

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


对 @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();

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

http://geekswithblogs.net/rakker/archive/2006/05/19/78952.aspx

您可以继承System.Reflection的“Attribute”类来创建您自己的“Description”类。像这样(来自 这里):

using System;
using System.Reflection;
namespace FunWithEnum
{
    enum Coolness : byte
    {
        [Description("Not so cool")]
        NotSoCool = 5,
        Cool, // since description same as ToString no attr are used
        [Description("Very cool")]
        VeryCool = NotSoCool + 7,
        [Description("Super cool")]
        SuperCool
    }
    class Description : Attribute
    {
        public string Text;
        public Description(string text)
        {
            Text = text;
        }
    }
    class Program
    {
        static string GetDescription(Enum en)
        {
            Type type = en.GetType();
            MemberInfo[] memInfo = type.GetMember(en.ToString());
            if (memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(Description), false);
                if (attrs != null && attrs.Length > 0)
                    return ((Description)attrs[0]).Text;
            }
            return en.ToString();
        }
        static void Main(string[] args)
        {
            Coolness coolType1 = Coolness.Cool;
            Coolness coolType2 = Coolness.NotSoCool;
            Console.WriteLine(GetDescription(coolType1));
            Console.WriteLine(GetDescription(coolType2));
        }
    }
}

您还可以看看这篇文章: http://www.codeproject.com/KB/cs/enumdatabinding.aspx

它专门与数据绑定相关,但展示了如何使用属性来修饰枚举值,并提供“GetDescription”方法来检索属性的文本。使用内置描述属性的问题是该属性还有其他用途/用户,因此描述可能会出现在您不希望的位置。自定义属性解决了这个问题。

我发现最好用下分来定义您的枚举值,这样 ThisIsValueA 将是 This_Is_Value_A 然后您可以执行 enumValue.toString().Replace("_"," ") 其中 enumValue 是您的变量。

添加的替代方法 Description 每个枚举属性都是创建一个扩展方法。要重新使用 Adam 的“Coolness”枚举:

public enum Coolness
{
    NotSoCool,
    Cool,
    VeryCool,
    SuperCool
}

public static class CoolnessExtensions
{
    public static string ToString(this Coolness coolness)
    {
        switch (coolness)
        {
            case Coolness.NotSoCool:
                return "Not so cool";
            case Coolness.Cool:
                return "Cool";
            case Coolness.VeryCool:
                return "Very cool";
            case Coolness.SuperCool:
                return Properties.Settings.Default["SuperCoolDescription"].ToString();
            default:
                throw new ArgumentException("Unknown amount of coolness", nameof(coolness));
        }
    }
}

虽然这意味着描述与实际值相距甚远,但它允许您使用本地化为每种语言打印不同的字符串,例如在我的 VeryCool 例子。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top