C# enum to string auto-conversion?

孤街醉人 提交于 2020-01-03 07:14:08

问题


Is it possible to have the compiler automatically convert my Enum values to strings so I can avoid explicitly calling the ToString method every time. Here's an example of what I'd like to do:

enum Rank { A, B, C }

Rank myRank = Rank.A;
string myString = Rank.A; // Error: Cannot implicitly convert type 'Rank' to 'string'
string myString2 = Rank.A.ToString(); // OK: but is extra work

回答1:


No. An enum is it's own type, if you want to convert it to something else, you have to do some work.

However, depending on what you're doing with it, some tasks will call ToString() on it automatically for you. For example, you can do:

Console.Writeline(Rank.A);



回答2:


You are not probably looking for enums itself, but a list of string constant. It can fit your needs better in some scenarios.

Use this instead:

public static class Rank
{
   public const string A = "A";
   public const string B = "B";
   public const string C = "C";
}



回答3:


No, but at least you can do things with enums that will call their ToString() methods when you might need to use their string value, e.g.:

Console.WriteLine(Rank.A); //prints "A".



回答4:


The correct syntax should be

myRank.ToString("F");



回答5:


[Caution, hack] Unsure as to whether this is nasty, to me it seems a reasonable compromise.

var myEnumAsString = MyEnum+""; Console.WriteLine(myEnumAsString); //MyEnum

This will force implicit ToString()



来源:https://stackoverflow.com/questions/3010641/c-sharp-enum-to-string-auto-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!