简体   繁体   中英

Comparing flags with flags - check for matches

Say I have an enum:

[Flags]
public enum Alpha
{
    NULL = 0,
    A0 = 1,
    A1 = 2,
    A2 = 4,
    A3 = 8
}

And I have the following:

Alpha selected = A0 | A1 | A2

Alpha compare = A1 | A3

I want to check if any of the selected flags are also in the compare flags.

The only way I can think to do this so far is (pseudocode)

foreach(Alpha flag in Enum.GetValues(typeof(Alpha)))
{
    if (selected.HasFlag(flag) && compare.HasFlag(flag))
    {
        return true
    }
}
return false

Is there a more logic-al way to do this?

Because it is treated as bit field, you can use it in the same fashion.

FlagsAttribute Class

Indicates that an enumeration can be treated as a bit field; that is, a set of flags

bool result = (selected & compare) > 0; // First solution
bool result2 = (selected & compare).Any(); // Second solution

您可能需要的是:

(selected & compare) > 0;

When you use an AND operator, any flag which is common between the two operands will be present in the result.

Then you just have to compare and see if the result is greater than Zero:

bool anySelected = (selected & compare) > 0;

我认为首先您应该从Alpha中删除NULL ,然后返回(selected & compare) != 0anyEnum.HasFlag(Alpha.NULL)将始终是正确的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM