更改枚举显示

10

如何在C#中创建一个枚举类型,使得将其转换为字符串时返回不同的字符串。与Java不同,C#似乎没有类似的功能。

public enum sample{
    some, other, things;

    public string toString(){
        switch(this){
          case some: return "you choose some";
          default: break;
        }
    }
}

Console.writeln(sample.some) 将输出:

you choose some

我只希望我的枚举在被调用时返回不同的字符串。


你尝试了什么?或者它在哪里出错了? - Kangkan
2
@Kangkan - 由于在C#中无法从枚举派生,因此没有直接尝试的方法... - Alexei Levenkov
4个回答

12
据我所知,这是不可能的。但是,您可以编写一个扩展方法来获取其他字符串:
public static class EnumExtensions
{
    public static string ToSampleString(this SampleEnum enum)
    {
         switch(enum)
         {
             case SampleEnum.Value1 : return "Foo";
             etc.
         }
    }
}

现在,只需在 SampleEnum 的实例上调用这个新的 ToSampleString 方法:

mySampleEnum.ToSampleString();

如果您对C#中的扩展方法不熟悉,请在此处阅读更多信息。

另一个选项是在每个enum值上方使用Description属性,如这里所述。


你可以结合枚举类的描述和枚举值来创建一个通用消息,然后使用扩展方法将其组合在一起。这样会使扩展方法更具可重用性。+1 - Phill
1
为什么检索Description属性如此复杂? - CodeCamper
1
获取Description属性只有一次比较复杂。您可以将其添加为扩展方法,并且可用于所有枚举,不再查看它。使用上面的答案,您将需要为每个枚举创建一个类似此方法的方法。您可以在此处查看一个不错的示例:http://weblogs.asp.net/stefansedich/archive/2008/03/12/enum-with-string-values-in-c.aspx - Nelson Reis
这真的,真的,真的不应该成为被接受的答案。使用属性是一种更优雅、面向对象、封装的解决方法。 - Bob Horn

4
我会通过创建一个属性来装饰枚举值,比如“描述”,使其具有装饰性。

例如:

public enum Rate
{
   [Description("Flat Rate")]
   Flat,
   [Description("Time and Materials")]
   TM
}

然后使用GetCustomAttributes来读取/显示这些值。http://msdn.microsoft.com/en-us/library/system.attribute.getcustomattributes.aspx @CodeCamper 抱歉回复晚了,下面是一些读取DescriptionAttribute的示例代码:
扩展方法:
public static class EnumExtensions
{
    public static string Description<T>(this T t)
    {
        var descriptionAttribute = (DescriptionAttribute) typeof (T).GetMember(t.ToString())
                                   .First().GetCustomAttribute(typeof (DescriptionAttribute));

        return descriptionAttribute == null ? "" : descriptionAttribute.Description;
    }
}

用法:

Rate currentRate = Rate.TM;
Console.WriteLine(currentRate.Description());

我一直在阅读关于如何做到这一点的文章,但似乎为某种原因过于复杂。您能否展示检索描述所需的最简单和最少行代码? - CodeCamper

3

您需要一个字典。枚举器为其值枚举(提供编号)。当您提供字符串键时,希望返回字符串值。尝试使用以下代码:

Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("some", "you choose some");
dictionary.Add("other", "you choose other");
dictionary.Add("things", "you choose things");

然后是这段代码:
string value = dictionary["some"];
Console.writeln(value);

将返回“你选择了一些”。

0

如果您只想将枚举转换为字符串,可以使用此方法:

Enum.GetName(typeof(sample), value);

这个方法将返回枚举的名称而不是整数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接