C# 枚举到字符串自动转换?
是否可以让编译器自动将我的 Enum 值转换为字符串,这样我就可以避免每次都显式调用 ToString 方法。这是我想做的一个例子:
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(6)
不。枚举是它自己的类型,因此如果您想将其转换为其他类型,您必须做一些工作。
但是,根据您使用它执行的操作,某些方法会自动为您调用
ToString()
。例如,您可以这样做:No. An enum is its own type, so 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 methods will call
ToString()
on it automatically for you. For example, you can do:您可能不是在寻找枚举本身,而是在寻找字符串常量列表。在某些场景下它可以更好地满足您的需求。
使用这个代替:
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:
不,但至少当您可能需要使用其字符串值时,您可以使用枚举来调用其
ToString()
方法,例如: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.:正确的语法应该是
The correct syntax should be
[警告,黑客] 不确定这是否令人讨厌,对我来说这似乎是一个合理的妥协。
var myEnumAsString = MyEnum+"";
Console.WriteLine(myEnumAsString); //我的枚举
这将强制隐式 ToString()
[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()
这个问题很多年前就被问过,但是尽管如此......
这是从枚举中获取 string[] 的非常简单的方法:
只需像这样使用它:
This question was asked many years ago, but nevertheless...
Here's a very easy way to get a string[] from an enum:
Simply use it like this: