c# - 为什么 MSDN 声明 HasFlag *设计*用于与 FlagsAttribute 一起使用?

标签 c# .net enums msdn enum-flags

问题 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/

相关文章:

c# - 组合框默认值 winforms c#

c# - 在 C# 中创建未压缩的 Zip

.net - 何时在计算表达式中实现 `Zero` 成员?

java - 如何将 String 转换为正确的 Enum 常量(实现公共(public)接口(interface)的多个 Enum)?

c# - 在 C# 中从当前窗体调用新窗体

c# - 寻找需要多个接口(interface)继承(而不是实现)的示例/案例

c++ - 将底层类型的任意值转换为强类型枚举类型是否安全?

methods - 从 struct 中快速调用方法

c# - 仅在禁用项目上显示 WPF 工具提示

c# - 升级到 .Net 4.0 后出现 AccessViolationException