How to Compare Flags in C#?

前端 未结 11 1754
我寻月下人不归
我寻月下人不归 2020-11-27 04:03

I have a flag enum below.

[Flags]
public enum FlagTest
{
    None = 0x0,
    Flag1 = 0x1,
    Flag2 = 0x2,
    Flag3 = 0x4
}

I cannot make

11条回答
  •  余生分开走
    2020-11-27 04:21

    One more piece of advice... Never do the standard binary check with the flag whose value is "0". Your check on this flag will always be true.

    [Flags]
    public enum LevelOfDetail
    {
        [EnumMember(Value = "FullInfo")]
        FullInfo=0,
        [EnumMember(Value = "BusinessData")]
        BusinessData=1
    }
    

    If you binary check input parameter against FullInfo - you get:

    detailLevel = LevelOfDetail.BusinessData;
    bool bPRez = (detailLevel & LevelOfDetail.FullInfo) == LevelOfDetail.FullInfo;
    

    bPRez will always be true as ANYTHING & 0 always == 0.


    Instead you should simply check that the value of the input is 0:

    bool bPRez = (detailLevel == LevelOfDetail.FullInfo);
    

提交回复
热议问题