五分鐘徹底弄懂特性

前言

在工做或者學習中,不免或多或少的接觸到特性這個東西,可能你不太清楚什麼是特性,那麼我給你們舉兩個例子 [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; }
    }

在定義特性類TableNameAttributethis

//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/特性

關於其餘我的筆記

  1. C# 使用RabbitMQ的完整圖解
  2. VS中進行編碼時智能提示由英文切換爲中文
  3. 開源項目-一沙後臺管理(core-mvc-緩存,支持多數據庫)
  4. ASP.NET Core中使用NLog記錄日誌
  5. Visual Studio中Git的使用
  6. [徹底圖解]NET Croe 使用JWT驗證簽名

分享最新的Net和Core相關技術以及實戰技巧,更重要的是分享Net項目,不容錯過的還有書籍,手寫筆記,壁紙分享 等。
在這裏插入圖片描述

相關文章
相關標籤/搜索