Should “or” work with .Net4 Hasflags: enum.HasFlag(AccessRights.Read | AccessRights.Write)

后端 未结 4 688
自闭症患者
自闭症患者 2020-12-31 06:58

I am trying out the new HasFlags features, and was wondering if the following should work:

enum.HasFlag(AccessRights.Read | AccessRights.Writ

4条回答
  •  隐瞒了意图╮
    2020-12-31 07:41

    Given the documentation, I'd expect that to return true if the value has both of those flags.

    If you want it to test whether your value has either of those flags, you'll need

    value.HasFlag(AccessRights.Read) | value.HasFlag(AccessRights.Write)
    

    If that's not good readable enough for you, you may want to look at my Unconstrained Melody project. It so happens that that already has the functionality you want (as extension methods in Flags.cs):

    // Same as value.HasFlag(AccessRights.Read | AccessRights.Write)
    value.HasAll(AccessRights.Read | AccessRights.Write)
    
    // Same as value.HasFlag(AccessRights.Read) | value.HasFlag(AccessRights.Write)
    value.HasAny(AccessRights.Read | AccessRights.Write)
    

    Those would make it clearer, IMO. They'd also avoid boxing, and be typesafe :)

提交回复
热议问题