开发者

C# Enum Reverse Indexing

开发者 https://www.devze.com 2023-03-25 09:30 出处:网络
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

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

精彩评论

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

关注公众号