How can I know items is in the enum?

强颜欢笑 提交于 2019-11-29 08:08:58

Your error lies in this method:

public static bool Contains(this QueryFlag flags, QueryFlag flag)
{
   return (flags & (~flag)) != flags;
}

This returns true whenever flags has any (i.e. at least one) of the flags contained in flag, but I think you want all.

It should read:

public static bool Contains(this QueryFlag flags, QueryFlag flag)
{
   return (flags & flag) == flag;
}

Alternatively, you can just use Enum.HasFlag() which does exactly this. For example:

QueryFlag qf = ...;
if (qf.HasFlag(QueryFlag.ByCustomer))
    // ...

A better way may be this:

return (flags & mask) == mask;

This will return true if all the flags set in mask are set in flags.

return (flags & mask) != 0;

This will return true is any of the flags set in mask are set in flags.

As for the generic method, you could try constraining the type to struct. This constrains T to being a value type.

public static bool Contains<T>(this T flags, T mask) where T : struct
{
    return (flags & mask) == mask;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!