C#枚举到字符串自动转换? [英] C# enum to string auto-conversion?

查看:121
本文介绍了C#枚举到字符串自动转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能让编译器自动将我的Enum值转换为字符串,所以我可以避免每次都显式调用ToString方法。这是我要执行的操作的示例:

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


推荐答案

否。枚举是它自己的类型,如果要将其转换为其他类型,则必须做一些工作。

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

但是,这取决于您在做什么。 ,有些任务会自动为您调用ToString()。例如,可以执行以下操作:

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);

这篇关于C#枚举到字符串自动转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆