更改枚举显示

scl*_*ang 10 c# oop enums coding-style

我怎么能有ac#enum,如果我选择字符串它返回一个不同的字符串,就像在java中它可以完成

public enum sample{
    some, other, things;

    public string toString(){
        switch(this){
          case some: return "you choose some";
          default: break;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

you choose some
Run Code Online (Sandbox Code Playgroud)

我只想让我的枚举在我尝试调用它们时返回不同的字符串.

Ben*_*ich 12

据我所知,这是不可能的.但是,您可以编写一个扩展方法来获取其他字符串:

public static class EnumExtensions
{
    public static string ToSampleString(this SampleEnum enum)
    {
         switch(enum)
         {
             case SampleEnum.Value1 : return "Foo";
             etc.
         }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,只需ToSampleString在以下实例上调用此新实例SampleEnum:

mySampleEnum.ToSampleString();
Run Code Online (Sandbox Code Playgroud)

如果您不熟悉扩展方法C#,请在此处阅读更多内容.

另一种选择是使用Description上述各属性enum值,如所描述这里.