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

后端 未结 11 1597
陌清茗
陌清茗 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 06:11

    Worth pointing out that simply providing some static overloads for all the integral types will work so long as you know you are working with a specific enum. They won't work if the consuming code is likewise operating on where t : struct

    If you need to deal with arbitrary (struct) T

    You cannot currently do a fast conversion of a generically typed struct into some alternate bitwise form (i.e. roughly speaking a reinterpret_cast) without using C++/CLI

    generic 
    where T : value class
    public ref struct Reinterpret
    {
        private:
        const static int size = sizeof(T);
    
        public:    
        static int AsInt(T t)
        {
            return *((Int32*) (void*) (&t));
        }
    }
    

    This will then let you write:

    static void IsSet(T value, T flags) where T : struct
    {
        if (!typeof(T).IsEnum)
            throw new InvalidOperationException(typeof(T).Name +" is not an enum!");
        Type t = Enum.GetUnderlyingType(typeof(T));
        if (t == typeof(int))
        {
             return (Reinterpret.AsInt(value) & Reinterpret.AsInt(flags)) != 0
        }
        else if (t == typeof(byte))
        {
             return (Reinterpret.AsByte(value) & Reinterpret.AsByte(flags)) != 0
        }
        // you get the idea...        
    }
    

    You cannot constrain to enums. But the mathematical validity of these methods do not change if they are used with non enum types so you could allow them if you can determine that they are convertible to a struct of the relevant size.

提交回复
热议问题