c# - System.Reflection.TypeAttributes 是带有 FlagsAttribute 的病态枚举类型吗?

标签 c# .net enums base-class-library enum-flags

<分区>

枚举类型 System.Reflection.TypeAttributes 显得相当病态。它带有 [Flags]属性并且有不少于四个常量零的同义词。从 Visual-Studio 生成的“元数据”:

#region Assembly mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\mscorlib.dll
#endregion

using System.Runtime.InteropServices;

namespace System.Reflection
{
  //
  // Summary:
  //     Specifies type attributes.
  [ComVisible(true)]
  [Flags]
  public enum TypeAttributes
  {
    //
    // Summary:
    //     Specifies that the class is not public.
    NotPublic = 0,
    //
    // Summary:
    //     Specifies that class fields are automatically laid out by the common language
    //     runtime.
    AutoLayout = 0,
    //
    // Summary:
    //     Specifies that the type is a class.
    Class = 0,
    //
    // Summary:
    //     LPTSTR is interpreted as ANSI.
    AnsiClass = 0,

    // (followed by non-zero members...)

为什么有人会在带有 FlagsAttribute 的枚举类型中使用四个名称来表示零? ?看起来真的很疯狂。

看看后果:

var x = default(System.Reflection.TypeAttributes);     // 0
var sx = x.ToString();                                 // "NotPublic"
var y = (System.Reflection.TypeAttributes)(1 << 20);   // 1048576
var sy = y.ToString();                                 // "AutoLayout, AnsiClass, Class, BeforeFieldInit"

这里是 x 的字符串表示,类型的零值,变为 "NotPublic" .而非零的字符串表示 y变成 "AutoLayout, AnsiClass, Class, BeforeFieldInit" .关于y , 请注意它只有一个位集 ( 1<<20 ) 和名称 BeforeFieldInit alone 正好说明了这一点。所有其他三个名字,AutoLayout, AnsiClass, Class, , 对值(value)的贡献为零。

这是怎么回事?

为什么要这样设计?

最佳答案

ToString() 表示在很大程度上是无关紧要的

当某些选项是非二进制时,这种模式很常见;例如,有 3 个可能的选项。在那种情况下,您可以指定 2 位来携带这 3 个选项(留下 4 个未使用),并且“默认”选项将(逻辑上)为 00。这意味着是的,0 将有多个同义词。

注意:这可能发生在纯二元选项中,如果枚举作者想让它更明确——因为调用者不需要知道哪些是“开”的,哪些是“关闭”。

基本上,不用担心 ToString()

关于c# - System.Reflection.TypeAttributes 是带有 FlagsAttribute 的病态枚举类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39919956/

相关文章:

java - Java 的枚举相对于旧的 "Typesafe Enum"模式的优势?

c# - 标志和 << 对枚举的操作? C#

c# - nHibernate,一个 n 层解决方案 + 征求意见

c# - 可能是GeoShape过滤器(NEST)中的错误

.net - ASP.Net MVC 4/5 - 在运行时刷新路由

围绕非托管 DLL 的 C# 包装器库要求在构建期间非托管 DLL 位于同一目录中

.net - WPF 中的 MVVM - UserControls 和 GMap.NET

java - 如何在java中使用for或while方法调用枚举?

c# - ASP.NET MVC 应用程序有 SecurityException

c# - 如何在Unity 3D中使音频静音?