C#文法之Attribute

來源:互聯網
上載者:User

標籤:

在c#中,定義類的成員,可以定義Property稱為屬性.Attribute就稱為特性.

 

在FCL中,有內建的Attribute.如:

Condition[Attribute]:在什麼條件可以調用.(只能作用於傳回值為void的方法上)

Obsolete:方法棄用.支援禁用.

代碼1:

class Program    {        static void Main(string[] args)        {            Func();            Console.ReadLine();        }        [Obsolete("you can use Func to replace this",true)]        private static void Test()        {            Console.WriteLine("noooo");        }        private static void Func()        {            Console.WriteLine("yesss");        }    }    class T    {        [Conditional("DEBUG")]        public static void M(string str)        {            Console.WriteLine("Method{0}", str);        }    }
內建Attribute

 

自訂Attribute:

代碼2:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]    public class HelpAttribute : Attribute    {        public HelpAttribute(string str)        {            HelpStr = str;        }        public string Name { get; set; }        public string HelpStr { get; set; }    }
自訂Attribute

AttributeTargets.Class:作用目標只能是類.

AllowMultiple:是否可以在一個元素上多次作用特性.

Inherited:當目標被繼承時,特性是否也繼承.

 

反射擷取類的Attribute資訊:

代碼3:

class Program    {        static void Main(string[] args)        {            var attrs = typeof(MyClass).GetCustomAttributes(false);            for (int i = 0; i < attrs.Length; i++)            {                var attr = attrs[i] as HelpAttribute;                if (attr != null) Console.WriteLine(attr.HelpStr + attr.Name);            }            Console.ReadLine();        }    }    [Help("good", Name = " class")]    class MyClass    {    }
反射擷取特性資訊

 

C#文法之Attribute

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.