五分鐘完全弄懂C#特性
前言
在工作或者學習中,難免或多或少的接觸到特性這個東西,可能你不太清楚什么是特性,那么我給大家舉兩個例子 [Obsolete],[HttpGet],[HttpPost],[Serizlized],[AuthorizeFilter] (總有你見過的一個吧) 。有沒有覺得好熟悉,下面跟著小趙一探究竟。
特性(Attribute)用于添加元數據,如編譯器指令和注釋、描述、方法、類等其他信息。
特性(Attribute)的名稱和值是在方括號內規定的,放置在它所應用的元素之前。positional_parameters 規定必需的信息,name_parameter 規定可選的信息。
特性的定義
特性的定義:直接或者間接的繼承 Attribute 類
定義完就直接可以在方法前面用 [CustomAttribute] 可以省略 Attribute 寫成[Custom]
在特性類上面的特性 /// AttributeTargets.All --可以修飾的應用屬性 /// AllowMultiple = true ---是否可以進行多次修飾 [AttributeUsage(AttributeTargets.All,AllowMultiple = true)]圖片
特性的使用
特性本身是沒有啥用,但是可以通過反射來使用,增加功能,不會破壞原有的封裝 通過反射,發現特性 --實例化特性--使用特性 通過特性獲取表名(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
- //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[1]https://github.com/PrideJoy/NetTemple/tree/master/%E7%89%B9%E6%80%A7