C#特性Attribute说明示例

特性(Attribute)是用于在运行时传递程序中各类元素(好比类、方法、属性、字段、结构、枚举、组件等)的行为信息的声明性标签。
AttributeUsage:描述如何使用自定义的Attribute类,规定了能够应用到的程序中的元素类型。
Conditional:对方法或者属性增长一个条件标记,依赖于指定的预约义是否存在。
Obsolete:标注过期的元素,不该该被使用。spa

下面是具体的使用例子,经过定义一个新的Attribute类来讲明分析。code

#define TestAttribute

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Reflection;

namespace StudyCSharpConsole
{
    //AttributeUsage:用来限制和描述自定义Attribute类,规定了Attribute类适用的应用范围。
    //下面指明:适用于类和方法,只容许指定一个Attribute实例,没法由派生类和重写成员继承。
    //后两个是可选的,默认设定为false。
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
    class NewAttribute : Attribute
    {
        private string name = string.Empty;
        private string version = string.Empty;
        private int count = 0;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public string Version
        {
            get { return version; }
            set { version = value; }
        }

        public int Count
        {
            get { return count; }
            set { count = value; }
        }
    }

    [New(Name = "TestClass", Version = "1.0.0", Count = 1)]
    class TestClass
    {
        [Conditional("TestAttribute")]
        public void TestMethod()
        {
            Console.WriteLine("TestMethod is run.");
        }

        [New(Name = "TestMethod2", Version = "1.0.1", Count = 2)]
        public void TestMethod2()
        {
            Console.WriteLine("TestMethod2 is run.");
        }

        //标注该方法不推荐使用,在调用处编译器当作错误处理(false的时候当作警告)
        [Obsolete("TestMethod3 is Obsolete.", true)]
        public void TestMethod3()
        {
            Console.WriteLine("TestMethod3 is run.");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            TestClass testClass = new TestClass();
            //此处会报相似于后面的编译错误(“TestMethod3()”已过期:“TestMethod3 is Obsolete.”)。
            //testClass.TestMethod3(); 

            //预约义了TestAttribute的场合,下面的方法会被调用,不然会忽略该方法的调用。
            testClass.TestMethod();

            //取得类的特性信息
            NewAttribute attr = (NewAttribute)Attribute.GetCustomAttribute(typeof(TestClass), typeof(NewAttribute));
            Console.WriteLine(attr.Name + "," + attr.Version + "," + attr.Count);

            //先取得类的方法列表
            MethodInfo[] methods = typeof(TestClass).GetMethods();
            foreach (MethodInfo method in methods)
            {
                //取得每一个方法的特性并显示。
                NewAttribute methodAttr = (NewAttribute) Attribute.GetCustomAttribute(method, typeof(NewAttribute));
                if (methodAttr == null)
                {
                    continue;
                }
                Console.WriteLine(methodAttr.Name + "," + methodAttr.Version + "," + methodAttr.Count);
            }
        }
    }
}
相关文章
相关标签/搜索