C#特性

来源:互联网 发布:郑州大学软件学院算211 编辑:程序博客网 时间:2024/05/24 06:28

C#特性

特性(Attribute)是用于在运行时传递程序中各种元素(比如类、方法、结构、枚举、组件等)的行为信息的声明性标签。

特性(Attribute)用于添加元数据,如编译器指令和注释、描述、方法、类等其他信息。元数据是程序中定义的类型的相关信息。 所有 .NET 程序集都包含一组指定的元数据,用于描述程序集中定义的类型和类型成员。 可以添加自定义特性来指定所需的其他任何信息

.NET框架中一些预定义的特性

  • Obsolete-标记某个type过时了
  • WebMethod-公开WebService方法
  • Serializable-表示某个类可以被序列化

Obsolete的使用参考Part 52 - C# Tutorial - Attributes in C#
例如,可以使用Obsolete标记某个方法已经过时了,提示其使用新的方法代替

[Obsolete("Use Add(List<int> Numbers) instead")]public static int Add(int FirstNumber, int SecondNumber)

Obsolete还有一个属性error,指定为true的话,就不是警告了,而是错误,甚至不能编译程序

[Obsolete("Use Add(List<int> Numbers) instead", true)]public static int Add(int FirstNumber, int SecondNumber)

AttributeUsage

参考:

  • C# 特性(Attribute)
  • AttributeUsage (C#)

AttributeUsage 是 AttributeUsageAttribute 的别名。

预定义特性 AttributeUsage 描述了如何使用一个自定义特性类。它规定了特性可应用到的项目的类型。

[System.AttributeUsage(System.AttributeTargets.All,                     AllowMultiple = false,                     Inherited = true)]  class NewAttribute : System.Attribute { }  

参数的含义:

  • AttributeUsage-规定特性可被放置的语言元素。默认是 AttributeTargets.All。必须是 AttributeTargets 枚举的一个或多个元素。 可将多个目标类型与 OR 运算符链接在一起,如下所示:

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]  class NewPropertyOrFieldAttribute : Attribute { } 
  • AllowMultiple-如果为 true,则该特性是多用的。默认值是 false(单用的)

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]  class MultiUseAttr : Attribute { }  [MultiUseAttr]  [MultiUseAttr]  class Class1 { }  [MultiUseAttr, MultiUseAttr]  class Class2 { } 
  • inherited-如果为 true,则该特性可被派生类继承。默认值是 false(不被继承)

自定义特性

参考:

  • 创建自定义特性 (C#)
  • C# 特性(Attribute)

可通过定义特性类创建自己的自定义特性,特性类是直接或间接派生自 Attribute 的类,可快速轻松地识别元数据中的特性定义。

创建并使用自定义特性包含四个步骤:

  • 声明自定义特性
  • 构建自定义特性
  • 在目标程序元素上应用自定义特性
  • 通过反射访问特性

自定义 Author 特性类

[System.AttributeUsage(System.AttributeTargets.Class |                         System.AttributeTargets.Struct)  ]  public class Author : System.Attribute  {      private string name;      public double version;      public Author(string name)      {          this.name = name;          version = 1.0;      }  } 

使用 AttributeUsage 特性可使 Author 特性仅对类和 struct 声明有效。

可按如下方式使用这一新特性:

[Author("P. Ackerman", version = 1.1)]  class SampleClass  {      // P. Ackerman's code goes here...  }