为什么我不能在变量和枚举 (C#) 之间进行比较

本文关键字:之间 比较 枚举 不能 变量 为什么 | 更新日期: 2023-09-27 18:34:31

我的参考代码:

uint bk = 0;
enum ButtonKey : uint
{
   None = 0,
   Key1,
   Key2
};
private void button_Click(object sender, EventArgs e)
{
    bk = (uint)ButtonKey.Key1;
}
void foo()
{
    if( bk == ButtonKey.Key1 )
    {
        // so something
    }
}

我在bk == ButtonKey.Key1比较中出现错误。 无论我如何尝试铸造两者,我都无法超越这一点。 我相信有一个简单的解释...那决心整天躲着我!

我在这里错过了什么?? 提前感谢...

为什么我不能在变量和枚举 (C#) 之间进行比较

您正在将uint与特定类型的enum进行比较。比较时强制转换枚举:

if( bk == (uint)ButtonKey.Key1 )
{
    // so something
}

更好的解决方案是更改bk的类型:

ButtonKey bk;
enum ButtonKey
{
   None = 0,
   Key1,
   Key2
};
private void button_Click(object sender, EventArgs e)
{
    bk = ButtonKey.Key1;
}
void foo()
{
    if( bk == ButtonKey.Key1 )
    {
        // so something
    }
}

您需要的是将枚举转换为代表 int 值,然后您可以比较它

if(bk == (uint) ButtonKey.Key1)
{
}