开发者

About the Enum operation

I have a enum like

enum Test
{ 
    A = -开发者_StackOverflow社区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 . (^^ メ)*


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
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜