开发者

C# Enum Reverse Indexing

Is there a way to use an integer index to return the appro开发者_如何学编程priate 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?


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"


You can cast your integer value to an enum.

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


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

Use the Enum.ToString() method.

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


It's klunky but...

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜