[英]Is there a solution for a bitwise logical AND (&) operator between two Enum values in C#
考虑 C# 中的以下简单标志枚举:
[Flags]
public enum CountingEnum
{
Zero = 0,
One = 1 << 0,
Two = 1 << 1,
Three = Two | One,
Four = 1 << 2,
Five = Four | One,
}
如果我想知道一个值是否包含另一个值,我可以使用按位逻辑 AND (&) 运算符编写一个简单的扩展方法。 这看起来很像 Enum.HasFlag,但我写出来是有原因的。 此方法需要知道 Enum 类型,而 HasFlag 仅适用于匹配的枚举类型。 我想要一个跨类型的通用解决方案:
public static class CountingEnumExtensions
{
public static bool Contains(this CountingEnum value, CountingEnum target)
{
return (value & target) == target;
}
}
这有助于使用一种简洁的语法来检查一个标志值是否包含另一个:
if (CountingEnum.Five.Contains(CountingEnum.Four))
{
// Yep!
}
if (CountingEnum.Four.Contains(CountingEnum.Five))
{
// Nope!
}
但是,如果我有另一个 Flags Enum 怎么办? 每次我想这样做时,我都可以制作另一种扩展方法,但这不是很可持续。 .HasFlag 也无济于事:
if (CountingEnum.Three.HasFlag(AnotherCountingEnum.One){
// System.ArgumentException
}
我可以在任何地方手动使用它,但它对于按位不识字的人来说不是很可读:
if ((SomeEnum.Value & SomeEnum.Target) == SomeEnum.Target)
{
// Dunno!
}
但是有没有通用的解决方案? 当然,以下内容不会编译,但它传达了我想要的想法:
public static class EnumExtensions
{
public static bool Contains(this Enum value, Enum target)
{
// Cannot apply operation '&' to operands of
// type 'System.Enum' and 'System.Enum'
return (value & target) == target;
}
}
是否有针对任何两个匹配类型的标志枚举值执行按位逻辑与的通用解决方案?
如果它们的符号不重要,可以尝试无符号整数类型转换。
public static bool Contains(this Enum value, Enum target)
{
uint y = Convert.ToUInt32(value);
uint z = Convert.ToUInt32(target)
return (y & z) == z;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.