What Does the [Flags] Attribute Really Do?

前端 未结 6 1225
闹比i
闹比i 2020-12-06 03:58

What does applying [Flags] really do?

I know it modifies the behavior of Enum.ToString, but does it do anything else? (e.g. Different compiler or runtime behavior, e

6条回答
  •  一向
    一向 (楼主)
    2020-12-06 04:36

    In practice, one of the uses I use is indicating multiple statuses. This is a simplification of some code that evaluates test results. The test can be Ok, or it could have several reasons for not being Ok. The advantage this gives, is I have one method that evaluates the tests "Ok-ness", and that method is able to indicate all the possible failure conditions with one return. May not be the best design, but it works in this case.

    [Flags]
    public enum ResultStatusEnum
    {
        Ok = 0x1,
        SampleInvalid = 0x2,
        DirectionInvalid = 0x4,
        TestIsNotValid = 0x8
    }
    

    You set it like this:

    ResultStatusEnum res = ResultStatusEnum.SampleInvalid | ResultStatusEnum.DirectionInvalid;
    

    The disadvantage is that checking the values of the enum becomes cumbersome. This won't (necessarily) work:

    res == ResultStatusEnum.Ok
    

    You have to do this to check:

    ResultStatusEnum.SampleInvalid == (res & ResultStatusEnum.SampleInvalid)
    

    In this case, its illogical to have ResultStatusEnum.Ok & ResultStatusEnum.SampleInvalid, but I just make sure this isn't the case where I use the enum.

提交回复
热议问题