菜鸟教程 C#特性 Attribute

C#文档 特性

说明

特性(Attribute)是提供了一种将元数据声明性信息代码(程序集、类型、方法、属性等)相互关联的强大方法。

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

特性具有以下属性:

  • 特性将元数据添加到程序中。元数据是有关程序中定义的类型的信息。所有.NET程序集都包含一组指定的元数据,这些元数据描述程序集中定义的类型和类型成员。
  • 可以将一个或多个特性应用于整个程序集、模块或较小的程序元素(如类和属性)
  • 属性可以采用与方法和属性相同的方式接受参数
  • 程序可以使用反射检查其自己的元数据或其他程序中的元数据

特效类型

.Net框架提供了两种类型的特性:预定义特性、自定义特性

预定义特性

AttributeUsage:描述如何使用一个自定义特性类(class xxxAttribute)。它规定了该特性可应用到的项目类型。

  1. [System.AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
  2. public class ClassInfoAttribute : System.Attribute
  3. {
  4. public string ClassDesc = "";
  5. public ClassInfoAttribute(string classDesc)
  6. {
  7. this.ClassDesc = classDesc;
  8. }
  9. }

Conditional:标记了一个条件方法,其依赖于制定的预处理标识符

#define Debug

using System;

namespace StudyCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            TestClassA.Print("TestClassA Conditional");
            Console.ReadLine();
        }
    }

    public class TestClassA
    {
        [System.Diagnostics.Conditional("Debug")]
        public static void Print(string content)
        {
            Console.WriteLine(content);
        }
    }
}

Obsolete:标记了不应该使用的程序实体。

对Attribute(特性)的说明与利用 - 图1

自定义特性

[System.AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class ClassDescAttribute : System.Attribute
{
    string Desc;
    public ClassDescAttribute(string desc)
    {
        Desc = desc;
    }
}

[ClassDescAttribute("这是一个测试类")]
public class TestClassA
{}

使用反射获取自定义特性的数据

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        TestClassA tca = new TestClassA();
        foreach (var item in tca.GetType().GetCustomAttributes(false))
        {
            ClassDescAttribute cda = item as ClassDescAttribute;
            if (cda != null)
            {
                Console.WriteLine(cda.Desc);
            }
        }
        Console.ReadLine();
    }
}

[System.AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class ClassDescAttribute : System.Attribute
{
    public string Desc;
    public ClassDescAttribute(string desc)
    {
        Desc = desc;
    }
}

[ClassDescAttribute("这是一个测试类")]
public class TestClassA
{}

对Attribute(特性)的说明与利用 - 图2