关于Enum操作

发布于 2024-12-03 20:10:58 字数 778 浏览 0 评论 0原文

我有一个像

enum Test
{ 
    A = -2,
    B = -1 , 
    C = 0 , 
    D = 1 , 
    E = 2
}

and 这样的枚举,我如何判断一个枚举值是在

class Program
{
    static void Main(string[] args)
    {
        Test t1 = Test.A | Test.E;

        Console.WriteLine((t1 & Test.E) > 0); // true
        Console.WriteLine((t1 & Test.A) > 0); // why this is false ?

        Console.ReadKey();
    }
}

我想问的组合枚举值中,为什么

Test t1 = Test.A | Test.E;

但是

Console.WriteLine((t1 & Test.A) > 0);

谢谢......

更新:

感谢您的评论,以及好的设计...

*我想我会像儿子一样尽快改变糟糕的设计! *

*仍然谢谢你们。 (^^メ)*

I have a enum like

enum Test
{ 
    A = -2,
    B = -1 , 
    C = 0 , 
    D = 1 , 
    E = 2
}

and , how can i judge a enum value is in a combine enum values

class Program
{
    static void Main(string[] args)
    {
        Test t1 = Test.A | Test.E;

        Console.WriteLine((t1 & Test.E) > 0); // true
        Console.WriteLine((t1 & Test.A) > 0); // why this is false ?

        Console.ReadKey();
    }
}

i want to ask about , why

Test t1 = Test.A | Test.E;

but

Console.WriteLine((t1 & Test.A) > 0);

Thanks....

UPDATE:

Thank you for your comment , and the good design...

*I think I will change the bad design as sonn as quickly!! *

*Thank you all the same . (^^ メ)*

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你如我软肋 2024-12-10 20:10:58

为了使其工作,您必须确保枚举值设置不同的位,因为您正在执行按位与运算。尝试像这样定义 Test

enum Test
{ 
    A = 1,
    B = 2, 
    C = 4, 
    D = 8, 
    E = 16
}

或者。

[Flags]
enum Test
{ 
    A = 0x1,
    B = 0x2, 
    C = 0x4, 
    D = 0x8, 
    E = 0x10
}

To make this work, you have to make sure that the enum-values set different bits since you are doing a bitwise-and operation. Try to define Test like this

enum Test
{ 
    A = 1,
    B = 2, 
    C = 4, 
    D = 8, 
    E = 16
}

Alternatively.

[Flags]
enum Test
{ 
    A = 0x1,
    B = 0x2, 
    C = 0x4, 
    D = 0x8, 
    E = 0x10
}
糖果控 2024-12-10 20:10:58

原因是 Test.A | Test.E 的计算结果为 -2 | 2 = -2,因此t1 == Test.A

现在t1 &测试.E = -2 & 2=2> 0 和
t1 &测试.A = -2 & -2=-2< 0

The reason is that Test.A | Test.E evaluates to -2 | 2 = -2, so t1 == Test.A.

Now t1 & Test.E = -2 & 2 = 2 > 0 and
t1 & Test.A = -2 & -2 = -2 < 0

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文