C#中屬性(Attribute)的用法
更新時(shí)間:2022年05月11日 15:11:20 作者:springsnow
這篇文章介紹了C#中屬性(Attribute)的用法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
一、創(chuàng)建屬性
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor, AllowMultiple = true, Inherited = true)] //AttributeTargets:屬性應(yīng)用到的目標(biāo)類型。AllowMultiple:是否允許一個(gè)元素應(yīng)用多個(gè)此屬性。Inherited:屬性能否有派生類繼承。 public class CodeStatusAttribute : Attribute { private string status; public CodeStatusAttribute(string status)//構(gòu)造函數(shù)為位置參數(shù) { this.status = status; } public string Tester { set; get; }//屬性和公共字段為命名參數(shù) public string Coder { set; get; } public override string ToString() { return status; } }
二、應(yīng)用屬性
//1、使用單個(gè)屬性 [CodeStatus("a版")] public class Tringe { } //2、使用多個(gè)屬性 [CodeStatus("b版", Coder = "小李")] [CodeStatus("b版", Coder = "小王")] //也可以[CodeStatus("aa",Coder="小李"),CodeStatus("aa",Coder="小王")] public class Square { } //3、使用位置參數(shù)和命名參數(shù) //type表示此屬性與什么元素關(guān)聯(lián),可能有:assembly,field,method,param,property,return,moudule,event,type等。。 [type: CodeStatus("最終版", Coder = "小李", Tester = "老李")] public class Circle { [CodeStatus("最終版", Coder = "小李", Tester = "老李")] public Circle() { } }
三、反射屬性
//1、獲取類上的屬性。 Type t = typeof(Circle); Attribute[] attArr = Attribute.GetCustomAttributes(t, typeof(CodeStatusAttribute)); //或 object[] attArr1 = t.GetCustomAttributes(typeof(CodeStatusAttribute), true); //2、獲取成員上屬性 Attribute[] attArr3 = t.GetConstructors()[0].GetCustomAttributes().ToArray();//構(gòu)造函數(shù),獲取字段GetField("..") //3、遍歷 foreach (Attribute attr in attArr3) { CodeStatusAttribute item = (CodeStatusAttribute)attr; Console.Write(item.ToString() + item.Coder + item.Tester); }
四、Net內(nèi)置屬性
[Condeitonal] //條件控制 [Obsolete] //廢棄屬性 [Serializable]//可序列化屬性 [AssemblyDelaySign] //程序集延遲簽名
到此這篇關(guān)于C#屬性(Attribute)的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
WinForm實(shí)現(xiàn)頁面按鈕定時(shí)隱藏功能
這篇文章主要介紹了WinForm實(shí)現(xiàn)頁面按鈕定時(shí)隱藏功能,結(jié)合實(shí)例形式分析了WinForm基于定時(shí)器的頁面控件屬性動(dòng)態(tài)操作相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-05-05C#設(shè)計(jì)模式之Mediator中介者模式解決程序員的七夕緣分問題示例
這篇文章主要介紹了C#設(shè)計(jì)模式之Mediator中介者模式解決程序員的七夕緣分問題,簡單說明了中介者模式的定義并結(jié)合七夕緣分問題實(shí)例分析了中介者模式的具體使用技巧,需要的朋友可以參考下2017-09-09C#調(diào)用打印機(jī)實(shí)現(xiàn)打印
這篇文章介紹了C#調(diào)用打印機(jī)實(shí)現(xiàn)打印的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-04-04C#反射在實(shí)際應(yīng)用中的實(shí)例代碼
C#反射在實(shí)際應(yīng)用中的實(shí)例代碼,需要的朋友可以參考一下2013-03-03C#將圖片和字節(jié)流互相轉(zhuǎn)換并顯示到頁面上
本文主要介紹用C#實(shí)現(xiàn)圖片轉(zhuǎn)換成字節(jié)流,字節(jié)流轉(zhuǎn)換成圖片,并根據(jù)圖片路徑返回圖片的字節(jié)流,有需要的朋友可以參考下2015-08-08親自教你實(shí)現(xiàn)棧及C#中Stack源碼分析
大家都知道棧的實(shí)現(xiàn)方式有兩種,一種是基于數(shù)組實(shí)現(xiàn)的順序棧,另一種是基于鏈表實(shí)現(xiàn)的鏈?zhǔn)綏?。這篇文章主要介紹了手把手教你實(shí)現(xiàn)棧以及C#中Stack源碼分析,需要的朋友可以參考下2021-09-09C# 運(yùn)算符 ?、??、?: 各種問號的用法和說明
本文介紹C#中三種常見的問號運(yùn)算符的使用方法,簡單講解給大家,希望對大家有所幫助。2016-04-04