C#拾遺系列(7):自訂屬性

來源:互聯網
上載者:User

1 .描述

屬性提供功能強大的方法以將聲明資訊與 C# 代碼(類型、方法、屬性等)相關聯。屬性與程式實體關聯後,即可在運行時使用名為“反射”的技術查詢屬性。

屬性以兩種形式出現:

  • 一種是在公用語言運行庫 (CLR) 中定義的屬性。

  • 另一種是可以建立的用於向代碼中添加附加資訊的自訂屬性。此資訊可在以後以編程方式檢索。

2. 範例程式碼:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace NetTest

{

    public class TestAttribute

    {

        public void Test()

        {           

            PrintAuthorInfo(typeof(CustomAttribute));       

        }

 

        /*

        Obsolete 屬性將某個程式實體標記為一個建議不再使用的實體。每次使用被標記為已淘汰的實體時,

        隨後將產生警告或錯誤,這取決於屬性是如何配置的,第二個參數是true時,編譯時間顯示錯誤

        */

        [Obsolete("please use aonther method,this is obsolate",true)]

        public void TestObsolate()

        {

            Console.Out.WriteLine("welcome");

 

        }

 

        private static void PrintAuthorInfo(System.Type t)

        {

            System.Console.WriteLine("Author information for {0}", t);

            System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);  // reflection

 

            foreach (System.Attribute attr in attrs)

            {

                if (attr is Author)

                {

                    Author a = (Author)attr;

                    System.Console.WriteLine("   {0}, version {1:f}", a.Name, a.version);

                }

            }

        }

 

        //應用自訂屬性

        [Author("Jack",version=1.0)]

        [Author("TJ",version=2.0)]

        class CustomAttribute

        {

            public void Test()

            {

 

                Console.Out.WriteLine("Test custom attribute");

            }       

        }

 

        //自訂的屬性,整合屬性類

        [System.AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct,AllowMultiple=true)]

        class Author : System.Attribute

        {

            private string name;

            public double version;

 

            public Author(string name)

            {

                this.name = name;

                version = 1.0;

            }

 

            public string Name

            {

 

                get { return this.name; }

            }

 

        }

    }

 

}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.