简体   繁体   中英

Check if more than one flag set in generic extension

Borrowing the code from this question How do I check if more than one enum flag is set? I have tried to implement a generic extension that performs this test.

My first attempt was the following.

public static bool ExactlyOneFlagSet(this Enum enumValue)
{
    return !((enumValue & (enumValue - 1)) != 0);
}

Which resulted in

Operator '-' cannot be applied to operands of type 'System.Enum' and 'int'

OK make sense, so I thought I'd try something like this

public static bool ExactlyOneFlagSet<T>(this T enumValue) where T : struct, IConvertible
{
    return !(((int)enumValue & ((int)enumValue - 1)) != 0);
}

Which resulted in

Cannot convert type 'T' to 'int'

Which also makes sense after reading about this behaviour but then how on earth can this extension method be implemented. Anyone kind enough to help???

Since you contrain T to implement IConvertible , you can simply call ToInt32 :

public static bool ExactlyOneFlagSet<T>(this T enumValue)
    where T : struct, IConvertible
{
    int v = enumValue.ToInt32(null);
    return (v & (v - 1)) == 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM