C#Enum索引问题

joh*_*ohn 3 c# indexing enums

是否可以使用索引整数来获取enum值?例如,如果......

public enum Days { Mon, Tues, Wed, ..., Sun};
Run Code Online (Sandbox Code Playgroud)

...在某种程度上可以写出类似......

Days currentDay = Days[index];
Run Code Online (Sandbox Code Playgroud)

谢谢!

Jam*_*are 6

没有,但你可以施放intenum,如果你使用的是值的定义enum,但你在你自己的风险这样做:

Days currentDay = (Days)index;
Run Code Online (Sandbox Code Playgroud)

如果你真的想要安全,你可以检查它是否首先定义,但这将涉及一些拳击等,并将阻尼性能.

// checks to see if a const exists with the given value.
if (Enum.IsDefined(typeof(Days), index))
{
    currentDay = (Days)index;
}
Run Code Online (Sandbox Code Playgroud)

如果您知道您的枚举是指定的连续值范围(即Mon = 0到Sun = 6),您可以比较:

if (index >= (int)Days.Mon && index <= (int)Days.Sun)
{
    currentDay = (Days) index;
}
Run Code Online (Sandbox Code Playgroud)

你也可以使用传回来的数组Enum.GetValues(),但是再一次这比演员更重:

Day = (Day)Enum.GetValues(typeof(Day))[index];
Run Code Online (Sandbox Code Playgroud)