当声明特定的枚举项时,强制转换枚举有效,但从字典中检索时无效
本文关键字:枚举 无效 有效 检索 字典 转换 声明 | 更新日期: 2023-09-27 18:26:27
当使用基类型uint声明枚举时,当您确切知道要转换的项时,可以将其强制转换为int。但是,当您有一个Dictionary并从中检索其中一个枚举项时,就不能执行此强制转换。
为什么会发生这种情况?
例如:
枚举:
public enum IncrementScheduleMask
{
Sunday = 0x01,
Monday = 0x02,
Tuesday = 0x04,
Wednesday = 0x08,
Thursday = 0x10,
Friday = 0x20,
Saturday = 0x40,
}
这将起作用:
bool Sun = true;
ulong weeklyMask = 0;
if (Sun)
weeklyMask |= (int)IncrementScheduleMask.Sunday;
但这个习惯:
public static List<string> DaysOfTheWeek = new List<string>{
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};
public static Dictionary<string, IncrementScheduleMask> DaysOfTheWeekMasks = new Dictionary<string, IncrementScheduleMask>()
{
{ "Sun", IncrementScheduleMask.Sunday },
{ "Mon", IncrementScheduleMask.Monday },
{ "Tue", IncrementScheduleMask.Tuesday },
{ "Wed", IncrementScheduleMask.Wednesday },
{ "Thu", IncrementScheduleMask.Thursday },
{ "Fri", IncrementScheduleMask.Friday },
{ "Sat", IncrementScheduleMask.Saturday }
};
ulong weeklyMask = 0;
Action<string> _CompileWeekDays = new Action<string>(dayName =>
{
IncrementScheduleMask iMask = DaysOfTheWeekMasks[dayName];
weeklyMask |= (int)iMask;
});
DaysOfTheWeek.ForEach(_CompileWeekDays);
我已经提出了另一个解决方案,但我想知道为什么其中一个有效,而另一个无效。如果你不能这样选演员,那么两种方式不应该都一样吗?
您的枚举基于int
,而不是您声称的uint
。
这两种情况的区别在于,在第一种情况下,您有一个常数转换。可以使用常量(文字)隐式地从int
转换为ulong
,因为编译器可以看到这些值是非负的。
在第二种情况下,您没有编译时间常数。因此,从int
(可能为负的类型)到ulong
(的无符号类型)的转换必须是显式的,而不是隐式的。
在这两种情况下,将(int)
强制转换为(ulong)
是很自然的。
这里有一个更简单的例子:
// will work:
const int e = 1;
ulong weeklyMask = e; // OK from int to ulong, constant
对比:
// will not work:
int e = 1;
ulong weeklyMask = e; // illegal from int to ulong, needs explicit cast