C#:Attribute類

Attribute

Attribute,作爲名詞,意思是標註,特徵的意思。我們經常在日常編碼中遇到,在某些類,方法,字段,屬性上面有如下情形:
        [AttributeTargets_All]
        public TestAttributeClass()
        {

        }

        [Obsolete("該方法已經停用!請使用Method2")]
        public void Method1()
        {
        }
即以一箇中括號包含進來的一些特殊的註解屬性,來修飾類,方法,字段,屬性。這些屬性可以是.net自帶的,也可以是用戶自定義出來的。

借鑑MSDN的解釋:
“公共語言運行時允許你添加類似關鍵字的描述聲明,叫做attributes, 它對程序中的元素進行標註,如類型、字段、方法和屬性等。Attributes和Microsoft .NET Framework文件的元數據保存在一起,可以用來向運行時描述你的代碼,或者在程序運行的時候影響應用程序的行爲。”

下面以一個簡單的示例,介紹一下Attribute的用法:
首先,自定義一些標註屬性:
    //AttributeTargets指定對哪些程序元素使用(如這裏是針對類)
    [AttributeUsage(AttributeTargets.Class)]
    public class AttributeTargets_ClassAttribute : Attribute
    {
    }

    //限制用在方法上面
    [AttributeUsage(AttributeTargets.Method)]
    public class AttributeTargets_MethodAttribute : Attribute
    {
        public AttributeTargets_MethodAttribute(string ctorStr)
        {
            this.testProperty = ctorStr;
        }
        public string testProperty { get; set; }
    }

    //限制用在方法和類上面
    [AttributeUsage(AttributeTargets.Method|AttributeTargets.Class)]
    public class AttributeTargets_MethodOrClassAttribute : Attribute
    {
    }

    //所有元素上都可以使用
    [AttributeUsage(AttributeTargets.All)]
    public class AttributeTargets_AllAttribute : Attribute
    {
    }

創建一個測試類:
    [AttributeTargets_Class]
    [AttributeTargets_MethodOrClass]
    [AttributeTargets_All]
    class TestAttributeClass
    {
        [AttributeTargets_All]
        public TestAttributeClass()
        {
        }

        [Obsolete("該方法已經停用!請使用Method2")]
        public void Method1()
        {
        }

        [AttributeTargets_Method("just for testing!")]
        public void Method2()
        {
        }

        [AttributeTargets_MethodOrClass]
        public void Method3()
        {
        }

        [AttributeTargets_All]
        public string MyProperty1 { get; set; }

        [AttributeTargets_All]
        public string MyProperty2 { get; set; }

        [AttributeTargets_All]
        public int MyFiled1 = 0;

        [AttributeTargets_All]
        public string MyFiled2 = "test";
    }

在該類中添加一個測試主函數:
     static void Main(string[] args)
        {
            Type classType = typeof(TestAttributeClass);

            Console.WriteLine("下面是獲得所有包含attribute的屬性:");
            foreach (PropertyInfo pro in classType.GetProperties())
            {
                foreach (Attribute attr in Attribute.GetCustomAttributes(pro))
                {
                    Console.WriteLine("Property:{0} have attribute:{1}", pro.Name, attr.ToString());
                }
                Console.WriteLine("---------------------------");
            }

            Console.WriteLine("下面獲得是所有包含attribute的字段:");
            foreach (FieldInfo field in classType.GetFields())
            {
                foreach (Attribute attr in Attribute.GetCustomAttributes(field))
                {
                    Console.WriteLine("Field:{0} have attribute:{1}", field.Name, attr.ToString());
                }
                Console.WriteLine("---------------------------");
            }
            Console.WriteLine("下面是獲得所有包含AttributeTargets_MethodAttribute註解屬性的方法及attribute中的屬性值:");
            foreach (MethodInfo method in classType.GetMethods())
            {
                foreach (Attribute attr in Attribute.GetCustomAttributes(method))
                {
                    //Console.WriteLine("Method:{0} have attribute:{1}",method.Name,attr.ToString());
                    if (attr.GetType() == typeof(AttributeTargets_MethodAttribute))
                    {
                        //Console.WriteLine("Method:{0} have attribute:{1}", method.Name, attr.ToString());
                        Console.WriteLine("Method:{0} have attribute:{1}", method.Name, ((AttributeTargets_MethodAttribute)attr).testProperty);
                    }
                }
                Console.WriteLine("---------------------------");
            }

            Console.WriteLine("下面是獲得Method1中ObsoleteAttribute註解屬性的只讀屬性Message:");
            ObsoleteAttribute obs = 
                (ObsoleteAttribute)Attribute.GetCustomAttribute(classType.GetMethod("Method1"), typeof(ObsoleteAttribute));
            Console.WriteLine("Method1 have attribute message:{0}",obs.Message);
        }
編譯運行,結果是:



實際上,獲得註解屬性主要通過.net的反射,Visual Studio中的Intelligence Edit也是通過反射來出提示的。
以上,關於attribute就記錄到此。
發佈了49 篇原創文章 · 獲贊 71 · 訪問量 23萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章