Anyone know a good workaround for the lack of an enum generic constraint?

后端 未结 12 1408
情书的邮戳
情书的邮戳 2020-11-22 15:37

What I want to do is something like this: I have enums with combined flagged values.

public static class EnumExtension
{
    public static bool IsSet

        
12条回答
  •  感动是毒
    2020-11-22 15:50

    Using your original code, inside the method you can also use reflection to test that T is an enum:

    public static class EnumExtension
    {
        public static bool IsSet( this T input, T matchTo )
        {
            if (!typeof(T).IsEnum)
            {
                throw new ArgumentException("Must be an enum", "input");
            }
            return (input & matchTo) != 0;
        }
    }
    

提交回复
热议问题