是否可以使用索引整数来获取enum
值?例如,如果......
public enum Days { Mon, Tues, Wed, ..., Sun};
......在某种程度上可以写出像...这样的东西。
Days currentDay = Days[index];
谢谢!
答案 0 :(得分:6)
不,但如果您使用的值在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;
}
如果您知道您的枚举是指定的连续值范围(即Mon = 0到Sun = 6),您可以比较:
if (index >= (int)Days.Mon && index <= (int)Days.Sun)
{
currentDay = (Days) index;
}
你也可以使用Enum.GetValues()
传回的数组,但这又比演员更重:
Day = (Day)Enum.GetValues(typeof(Day))[index];
答案 1 :(得分:0)
如果你正确地索引你的枚举,你可以只将int(或任何索引)作为枚举。
因此...
public enum Days { Mon = 0, Tue, Wed .... }
Days today = (Days)1;
答案 2 :(得分:0)
之前我必须使用DaysOfWeek
枚举进行一些计算。我使用扩展方法创建了一个安全的默认值。
以下是一个例子:
public enum Days { Invalid = ~0, Mon, Tues, Wed, Thurs, Fri, Sat, Sun };
class Program
{
static void Main(string[] args)
{
int day = 8;
Days day8 = (Days)day;
Console.WriteLine("The eighth day is {0}", day8);
Console.WriteLine("Days contains {0}: {1}",
day, Enum.IsDefined(typeof(Days), day));
Console.WriteLine("Invalid day if {0} doesn't exist: {1}",
day, day8.OrDefault(Days.Invalid) );
Console.WriteLine("Sunday day if {0} doesn't exist: {1}",
day, day8.OrDefault(Days.Sun));
Days day9 = ((Days)9).OrDefault(Days.Wed);
Console.WriteLine("Day (9) defaulted: {1}", 9, day9);
Console.ReadLine();
}
}
public static class DaysExtensions
{
public static Days OrDefault(this Days d, Days defaultDay)
{
if (Enum.IsDefined(typeof(Days), (Days)d))
{
return d;
}
return defaultDay;
}
}
输出:
The eighth day is 8
Days contains 8: False
Invalid day if 8 doesn't exist: Invalid
Sunday day if 8 doesn't exist: Sun
Day (9) defaulted: Wed