五分鍾完全弄懂特性


前言

在工作或者學習中,難免或多或少的接觸到特性這個東西,可能你不太清楚什么是特性,那么我給大家舉兩個例子 [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
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項目,不容錯過的還有書籍,手寫筆記,壁紙分享 等。
在這里插入圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM