在工做或者學習中,不免或多或少的接觸到特性這個東西,可能你不太清楚什麼是特性,那麼我給你們舉兩個例子 [Obsolete],[HttpGet],[HttpPost],[Serizlized],[AuthorizeFilter] (總有你見過的一個吧) 。有沒有以爲好熟悉,下面跟着小趙一探究竟。git
特性(Attribute)用於添加元數據,如編譯器指令和註釋、描述、方法、類等其餘信息。github
特性(Attribute)的名稱和值是在方括號內規定的,放置在它所應用的元素以前。positional_parameters 規定必需的信息,name_parameter 規定可選的信息。數據庫
特性的定義:直接或者間接的繼承 Attribute 類緩存
定義完就直接能夠在方法前面用 [CustomAttribute] 能夠省略 Attribute 寫成[Custom]mvc
在特性類上面的特性
/// AttributeTargets.All --能夠修飾的應用屬性
/// AllowMultiple = true ---是否能夠進行屢次修飾
[AttributeUsage(AttributeTargets.All,AllowMultiple = true)]
ide
特性自己是沒有啥用,可是能夠經過反射來使用,增長功能,不會破壞原有的封裝
經過反射,發現特性 --實例化特性--使用特性
經過特性獲取表名(orm)就是一個很好的案例函數
首先定義個類,僞裝和數據庫中的表結構同樣,但代表是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
this
//1.聲明 public class TableNameAttribute:Attribute { private string _name = null; //初始化構造函數 public TableNameAttribute(string tablename) { this._name = tablename; } public string GetTableName() { return this._name; } }
而後再student前面加上自定義特性
實現特性的擴展方法編碼
//經過反射獲取表名 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執行,查看運行結果
特性自己是沒有啥用,可是能夠經過反射來使用,增長功能,不會破壞原有的封裝
項目我放再個人github
https://github.com/PrideJoy/NetTemple/tree/master/特性
分享最新的Net和Core相關技術以及實戰技巧,更重要的是分享Net項目,不容錯過的還有書籍,手寫筆記,壁紙分享 等。