2013-02-15 47 views
0

所以System.Type有一个实例方法称为AttributesC#的Type.Attribute如何工作?

public TypeAttributes Attributes { get; } 

返回TypeAttributes类型的enum。下面是该枚举的一些成员:

public enum TypeAttributes { 
    AnsiClass = 0, 
    Class = 0, 
    AutoLayout = 0, 
    NotPublic = 0, 
    Public = 1, 
    NestedPublic = 2, 
    NestedPrivate = 3, 
    NestedFamily = 4, 
    NestedAssembly = 5, 
    NestedFamANDAssem = 6, 
    VisibilityMask = 7, 
    NestedFamORAssem = 7, 
    SequentialLayout = 8, 
    ExplicitLayout = 16, 
    LayoutMask = 24, 
... 
} 

但在另一方面,Type类有提供太多的属性大部分的东西出现在此枚举:

  • IsPublic
  • IsClass
  • IsNestedFamANDAssem
  • IsAutoLayout
  • ...

那么到底什么是Type.Attributes?我想这不是一个bitmasked值,因为它是一个枚举,它只返回一个枚举的成员。并且这不是Type类的静态属性,那么它究竟做了什么?

回答

2

Type.Attributes是一个位掩码值。它甚至says so in the documentation

enum s通常用Flags属性修饰它们作为标志数据类型。

而那些Type的属性,如IsPublic,IsClass等只是检查这些标志并返回一个布尔值。您可以通过使用反射镜查看定义自己看到它。

IsPublic,例如做这样的事情:

public bool IsPublic { 
    get { 
     return ((this.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.Public); 
    } 
} 

不是Type所有属性一定代表虽然标志之一(如IsEnum)。

+0

它为什么保持它是一个毫无意义的枚举,而不是将它变成int类型的? – 2013-02-18 21:53:12

+1

@ahmetalpbalkan - 你是什么意思“无意义的枚举”? “int”会如何变得更有意义? – 2013-02-19 06:36:38

2

我想这不是一个bitmasked值

你猜错了。它被标记为FlagsAttribute

指示一个枚举可以被视为一个位域;也就是一组标志。

如您所示,其中许多属性也可用。那么,为什么暴露?那么,首先,因为这是这些信息的自然表现。这些属性(例如IsPublic)只是为您隐藏测试。其次,有时候传递比布尔变量更方便。

1

据bitmasked值,其中值的部分代表类型的partiular性能 - 从枚举

  • myType.Attributes & TypeAttributes.LayoutMask给你

    • myType.Attributes & TypeAttributes.VisibilityMask给你一个数公开/非公开/ NestedPublic的...值布局类型(Sequential/Explicit/default)

    等等。