0

当使用基本类型 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);

我已经提出了另一种解决方案,但我想知道为什么一个有效,而另一个无效。如果你不应该像这样施放,那这两种方式不应该一样吗?

4

1 回答 1

0

您的枚举基于int,而不是uint您声称的。

这两种情况之间的区别在于,在第一种情况下,你有一个不断的转换。您可以使用常量(文字)隐式转换 from intulong因为编译器可以看到这些值是非负的。

在第二种情况下,您没有编译时常量。因此,从可能为负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
于 2013-08-05T21:17:24.140 回答