C#, Flags Enum, Generic function to look for a flag

后端 未结 11 1569
陌清茗
陌清茗 2020-12-30 05:43

I\'d like one general purpose function that could be used with any Flags style enum to see if a flag exists.

This doesn\'t compile, but if anyone has a suggestion, I

11条回答
  •  鱼传尺愫
    2020-12-30 05:59

    Why not write an extension method for this? I did this in another post

    public static class EnumerationExtensions {
    
        public static bool Has(this System.Enum type, T value) {
            try {
                return (((int)(object)type & (int)(object)value) == (int)(object)value);
            } 
            catch {
                return false;
            }
        }
        //... etc...
    
    }
    
    //Then use it like this
    bool hasValue = permissions.Has(PermissionTypes.Delete);
    

    It could use a little refinement (since it assumes everything can be cast as an int), but it could get you started...

提交回复
热议问题