C# 枚举反向索引

发布于 2024-11-27 04:46:22 字数 96 浏览 2 评论 0原文

有没有办法使用整数索引从枚举返回适当的值?例如,如果有枚举 Color {Red,Green,Blue) 是否有一个函数,对于值 0 将返回红色,1 将返回绿色,2 将返回蓝色?

Is there a way to use an integer index to return the appropriate value from an enum? For example, if there is the enum Color {Red, Green, Blue) is there a function that for the value 0 will return Red, 1 will return Green, and 2 will return Blue?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

回心转意 2024-12-04 04:46:22

Enum.GetName 方法: http://msdn.microsoft.com /en-us/library/system.enum.getname.aspx

使用您的示例,

Console.WriteLine(Enum.GetName(typeof(Color), 1));

打印“绿色”

The Enum.GetName method: http://msdn.microsoft.com/en-us/library/system.enum.getname.aspx

Using your example,

Console.WriteLine(Enum.GetName(typeof(Color), 1));

prints "Green"

人心善变 2024-12-04 04:46:22

您可以将整数值转换为枚举。

Color c = (Color)0; //Color.Red

You can cast your integer value to an enum.

Color c = (Color)0; //Color.Red
冰雪之触 2024-12-04 04:46:22
string color = ((Color)1).ToString(); //color is "Green"

使用 Enum.ToString() 方法。

http://msdn.microsoft.com/en-us/library/16c1xs4z.aspx

string color = ((Color)1).ToString(); //color is "Green"

Use the Enum.ToString() method.

http://msdn.microsoft.com/en-us/library/16c1xs4z.aspx

层林尽染 2024-12-04 04:46:22

这很笨拙,但是...

String Day = Enum.GetName(typeof(DayOfWeek), 3);

It's klunky but...

String Day = Enum.GetName(typeof(DayOfWeek), 3);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文