五分鐘完全弄懂C#特性
前言
在工作或者學(xué)習(xí)中,難免或多或少的接觸到特性這個(gè)東西,可能你不太清楚什么是特性,那么我給大家舉兩個(gè)例子 [Obsolete],[HttpGet],[HttpPost],[Serizlized],[AuthorizeFilter] (總有你見(jiàn)過(guò)的一個(gè)吧) 。有沒(méi)有覺(jué)得好熟悉,下面跟著小趙一探究竟。
特性(Attribute)用于添加元數(shù)據(jù),如編譯器指令和注釋、描述、方法、類(lèi)等其他信息。
特性(Attribute)的名稱(chēng)和值是在方括號(hào)內(nèi)規(guī)定的,放置在它所應(yīng)用的元素之前。positional_parameters 規(guī)定必需的信息,name_parameter 規(guī)定可選的信息。
特性的定義
特性的定義:直接或者間接的繼承 Attribute 類(lèi)
定義完就直接可以在方法前面用 [CustomAttribute] 可以省略 Attribute 寫(xiě)成[Custom]
在特性類(lèi)上面的特性 /// AttributeTargets.All --可以修飾的應(yīng)用屬性 /// AllowMultiple = true ---是否可以進(jìn)行多次修飾 [AttributeUsage(AttributeTargets.All,AllowMultiple = true)]圖片
特性的使用
特性本身是沒(méi)有啥用,但是可以通過(guò)反射來(lái)使用,增加功能,不會(huì)破壞原有的封裝 通過(guò)反射,發(fā)現(xiàn)特性 --實(shí)例化特性--使用特性 通過(guò)特性獲取表名(orm)就是一個(gè)很好的案例
首先定義個(gè)類(lèi),假裝和數(shù)據(jù)庫(kù)中的表結(jié)構(gòu)一樣,但表明是t_student 可以通過(guò)兩個(gè)方法來(lái)獲取表名(方法1加字段,或者擴(kuò)展方法tostring,但都破壞了以前的封裝,不提倡這樣做),然后就用到今天學(xué)習(xí)的特性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; }
- }
在定義特性類(lèi)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前面加上自定義特性
實(shí)現(xiàn)特性的擴(kuò)展方法
- //通過(guò)反射獲取表名
- 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í)行,查看運(yùn)行結(jié)果
總結(jié)
特性本身是沒(méi)有啥用,但是可以通過(guò)反射來(lái)使用,增加功能,不會(huì)破壞原有的封裝 項(xiàng)目我放在我的github[1]https://github.com/PrideJoy/NetTemple/tree/master/%E7%89%B9%E6%80%A7