您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“C#特性有哪些”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!
在工作或者學習中,難免或多或少的接觸到特性這個東西,可能你不太清楚什么是特性,那么我給大家舉兩個例子 [Obsolete],[HttpGet],[HttpPost],[Serizlized],[AuthorizeFilter] (總有你見過的一個吧) 。有沒有覺得好熟悉,下面跟著小趙一探究竟。
特性(Attribute)用于添加元數(shù)據(jù),如編譯器指令和注釋、描述、方法、類等其他信息。
特性(Attribute)的名稱和值是在方括號內(nèi)規(guī)定的,放置在它所應(yīng)用的元素之前。positional_parameters 規(guī)定必需的信息,name_parameter 規(guī)定可選的信息。
特性的定義:直接或者間接的繼承 Attribute 類
定義完就直接可以在方法前面用 [CustomAttribute] 可以省略 Attribute 寫成[Custom]
在特性類上面的特性 /// AttributeTargets.All --可以修飾的應(yīng)用屬性 /// AllowMultiple = true ---是否可以進行多次修飾 [AttributeUsage(AttributeTargets.All,AllowMultiple = true)]圖片
特性本身是沒有啥用,但是可以通過反射來使用,增加功能,不會破壞原有的封裝 通過反射,發(fā)現(xiàn)特性 --實例化特性--使用特性 通過特性獲取表名(orm)就是一個很好的案例
首先定義個類,假裝和數(shù)據(jù)庫中的表結(jié)構(gòu)一樣,但表明是t_student 可以通過兩個方法來獲取表名(方法1加字段,或者擴展方法tostring,但都破壞了以前的封裝,不提倡這樣做),然后就用到今天學習的特性attribute了
public class Student { //public static string tablename = "t_student"; //public string tostring() //{ // return "t_student"; //} public int id { get; set; } public string Name { get; set; } public int Sex { get; set; } }
在定義特性類TableNameAttribute
//1.聲明 public class TableNameAttribute:Attribute { private string _name = null; //初始化構(gòu)造函數(shù) public TableNameAttribute(string tablename) { this._name = tablename; } public string GetTableName() { return this._name; } }
然后再student前面加上自定義特性
實現(xiàn)特性的擴展方法
//通過反射獲取表名 public static string GetName(Type type) { if (type.IsDefined(typeof(TableNameAttribute),true)) { TableNameAttribute attribute =(TableNameAttribute)type.GetCustomAttribute(typeof(TableNameAttribute), true); return attribute.GetTableName(); } else { return type.Name; } }
F5執(zhí)行,查看運行結(jié)果
“C#特性有哪些”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。