不能为通用枚举参数应用“&”运算符
Posted
技术标签:
【中文标题】不能为通用枚举参数应用“&”运算符【英文标题】:Cannot apply '&' operator for generic Enum parameters 【发布时间】:2019-02-15 04:46:28 【问题描述】:我正在尝试为标志样式枚举编写一些通用扩展方法。从 C# 7.3 开始,TFlag 类型参数可以标记为 Enum,但编译器会为表达式 flags & flagToTest
抛出错误,它表示“运算符 '&' 不能应用于类型 TFlag 和 TFlag”。由于 TFlag 是一个 Enum,'&' 运算符应该可以正常工作。
public static bool IsSet<TFlag>(this TFlag flags, TFlag flagToTest) where TFlag : Enum
if (!Attribute.IsDefined(typeof(TFlag), typeof(FlagsAttribute)))
throw new InvalidOperationException("The given enum type is not decorated with Flag attribute.");
if (flagToTest.Equals(0))
throw new ArgumentOutOfRangeException(nameof(flagToTest), "Value must not be 0");
return (flags & flagToTest) == flagToTest;
【问题讨论】:
我认为枚举实例上有一个“HasFlag”方法,您可以调用它来提供此功能。它们确实需要“标志”属性,就像您的代码检查一样。 【参考方案1】:首先,看看这个答案https://***.com/a/50219294/6064728。 你可以用这种方式或类似的方式编写你的函数:
public static bool IsSet<TFlag>(this TFlag flags, TFlag flagToTest) where TFlag : Enum
if (!Attribute.IsDefined(typeof(TFlag), typeof(FlagsAttribute)))
throw new InvalidOperationException("The given enum type is not decorated with Flag attribute.");
if (flagToTest.Equals(0)) throw new ArgumentOutOfRangeException(nameof(flagToTest), "Value must not be 0");
int a = Convert.ToInt32(flags);
int b = Convert.ToInt32(flagToTest);
return (a & b) == b;
【讨论】:
以上是关于不能为通用枚举参数应用“&”运算符的主要内容,如果未能解决你的问题,请参考以下文章