C# 特性 Attribute

特性(Attribute)是用于在运行时传递程序中各种元素(比如类、方法、结构、枚举、组件等)的行为信息的声明性标签。您可以通过使用特性向程序添加声明性信息。一个声明性标签是通过放置在它所应用的元素前面的方括号([ ])来描述的。

特性(Attribute)用于添加元数据,如编译器指令和注释、描述、方法、类等其他信息。.Net 框架提供了两种类型的特性:预定义特性和自定义特性。

特性像是标签,告诉程序运行中元素的信息。

 

特性的定义

[AttributeUsage(
   validon,
   AllowMultiple=allowmultiple,
   Inherited=inherited
)]
  • 参数 validon 规定特性可被放置的语言元素。它是枚举器 AttributeTargets 的值的组合。默认值是 AttributeTargets.All
  • 参数 allowmultiple(可选的)为该特性的 AllowMultiple 属性(property)提供一个布尔值。如果为 true,则该特性是多用的。默认值是 false(单用的)。
  • 参数 inherited(可选的)为该特性的 Inherited 属性(property)提供一个布尔值。如果为 true,则该特性可被派生类继承。默认值是 false(不被继承)。

 

我们来创建一个特性,特性用Class创建,参数的传递用构造函数的参数和属性接收。例如

[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute
{
    public readonly string Url;   
    public string Topic { get; set; }   // Topic 是一个命名(named)参数 
    public HelpAttribute(string url)  // url 是一个定位(positional)参数
    {
        this.Url = url;
    }
}

创建个一个特性为HelpAtterbute的类,构造函数中的参数是必须要添加的,属性参数是可选参数。

[HelpAttribute("Information on the class MyClass", Topic = "MyClass Topic")] 
class MyClass
{
}

我们想要检索特性信息时候,需要用到反射(System.Reflection)

void Run(){
    System.Reflection.MemberInfo info = typeof(MyClass);
    object[] attributes = info.GetCustomAttributes(true);
    for (int i = 0; i < attributes.Length; i++)
    {
        System.Console.WriteLine(((HelpAttribute)attributes[i]).Url);    //输出Information on the class MyClass
        System.Console.WriteLine(((HelpAttribute)attributes[i]).Topic);  //输出MyClass Topic
    } 
}

 

 

posted on 2019-06-20 16:59  马什么梅  阅读(205)  评论(0编辑  收藏  举报

导航