问题 What does the [Flags] Enum Attribute mean in C#? 不问我在问什么,也不回答。如果该问题有这样的答案,请在评论中说明是哪一个(链接),而不是盲目和错误地标记为重复。
在 MSDN 的 HasFlag 上有这个注释文档:
The HasFlag method is designed to be used with enumeration types that are marked with the FlagsAttribute attribute and can be used to determine whether multiple bit fields are set. For enumeration types that are not marked with the FlagsAttribute attribute, call either the Equals method or the CompareTo method.
但我已经对其进行了测试,尽管使用 FlagsAttribute 标记或未标记枚举,但该方法工作正常.
也许文档上的注释只是试图通过使用属性来强制执行某种*良好实践*(最终根本无关紧要)?
我看了一眼here并且它确实似乎对枚举没有任何限制(它只是一个简单的按位与):
public Boolean HasFlag(Enum flag) {
if (!this.GetType().IsEquivalentTo(flag.GetType())) {
throw new ArgumentException(Environment.GetResourceString("Argument_EnumTypeDoesNotMatch", flag.GetType(), this.GetType()));
}
ulong uFlag = ToUInt64(flag.GetValue());
ulong uThis = ToUInt64(GetValue());
return ((uThis & uFlag) == uFlag);
}
那么,到底为什么说它*设计*与 FlagsAttribute 一起工作,而实际上它并不依赖它?
最佳答案
HasFlags
仅对 Flags
枚举有意义。您不必将枚举声明为 Flags
,但建议这样做。它是文档,它启用标志 ToString
格式。
MSDN 建议您或者创建一个标志枚举,将其标记为Flags
并使用HasFlags
,或者做都不是。不要混合。
这就是这句话试图传达的全部内容。它会插入您采用最佳实践。理想情况下,会有一个指向解释标志的页面的链接,但这不是 MSDN 通常处理的方式(唉)。它们主要是告诉您可以做什么,而不是应该做什么。
关于c# - 为什么 MSDN 声明 HasFlag *设计*用于与 FlagsAttribute 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20971714/