c# - 将枚举转换为字符串的最佳实践方法是什么?

标签 c# string enums

我有这样的枚举:

public enum ObectTypes
{
    TypeOne,
    TypeTwo,
    TypeThree,
    ...
    TypeTwenty
 }

然后我需要将这个枚举转换为字符串。现在我这样做:

public string ConvertToCustomTypeName(ObjectTypes typeObj)
{
    string result = string.Empty;
    switch (typeObj)
    {
        case ObjectTypes.TypeOne: result = "This is type T123"; break;
        case ObjectTypes.TypeTwo: result = "Oh man! This is type T234"; break;
        ...
        case ObjectTypes.TypeTwenty: result = "This is type last"; break;
    }

    return result;
}

我很确定有更好的方法来做到这一点,我正在寻找一些好的实践解决方案。

编辑:结果字符串中没有一个模式。

提前致谢。

最佳答案

我使用 System.ComponentModel 中的 [Description] 属性

例子:

public enum RoleType
{
    [Description("Allows access to public information")] Guest = 0,
    [Description("Allows access to the blog")] BlogReader = 4,
}

然后我会从中读取

public static string ReadDescription<T>(T enumMember)
{
    var type = typeof (T);

    var fi = type.GetField(enumMember.ToString());
    var attributes = (DescriptionAttribute[]) 
            fi.GetCustomAttributes(typeof (DescriptionAttribute), false);
    return attributes.Length > 0 ? 
        attributes[0].Description : 
        enumMember.ToString();
}

然后使用

ReadDescription(RoleType.Guest);

注意:此解决方案假定单一文化应用程序,因为没有特别询问有关多种文化的问题。如果您处于需要处理多种文化的情况,我会使用 DescriptionAttribute 或类似的方法来存储文化感知资源文件的 key 。虽然您可以将枚举成员直接存储在 .resx 文件中,这将创建尽可能紧密的耦合。我看不出您为什么要将应用程序的内部工作(枚举成员名称)与为国际化目的而存在的键值耦合。

关于c# - 将枚举转换为字符串的最佳实践方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2556759/

相关文章:

html - 在Swift 2.0中读取HTML文件

python - 给定一个字符串列表,每个字符串都由用逗号分隔的子字符串组成,如何对子字符串重新排序?

传递枚举和字符串可变参数的 Java 错误

java - 如何将枚举干净地链接到类中的静态信息?

Python 混合枚举作为字典键 : how the type is converted?

c# - LINQ 按名称选择属性

c# - parseexact 时,字符串未被识别为有效的 DateTime

c# - 在 c# metro 应用程序中创建 3D 立方体

c# - 在哪里存储将在我的应用程序中使用的常量对象

c# - 替代 .ToList() 以返回大量数据?