是否可以使用索引整数来获取 enum
值?例如,如果...
public enum Days { Mon, Tues, Wed, ..., Sun};
...是否有可能写出...
Days currentDay = Days[index];
谢谢!
最佳答案
不可以,但是您可以将 int
转换为 enum
,如果您使用的值是在 enum
中定义的,但是您这样做需要您自担风险:
Days currentDay = (Days)index;
如果你真的想要安全,你可以先检查它是否被定义,但这会涉及一些装箱等,并且会降低性能。
// checks to see if a const exists with the given value.
if (Enum.IsDefined(typeof(Days), index))
{
currentDay = (Days)index;
}
如果您知道您的枚举是指定的、连续的值范围(即周一 = 0 到周日 = 6),您可以比较:
if (index >= (int)Days.Mon && index <= (int)Days.Sun)
{
currentDay = (Days) index;
}
您还可以使用由 Enum.GetValues()
传回的数组,但这再次比强制转换更重:
Day = (Day)Enum.GetValues(typeof(Day))[index];
关于C# 枚举索引问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7490728/