1. 程式人生 > >C# 自定義特性Attribute

C# 自定義特性Attribute

一、特性Attribute和註釋有什麼區別

特性Attribute

  A:就是一個類,直接繼承/間接繼承Attribute

  B:特性可以在後期反射中處理,特性本身是沒有什麼*用的

  C:特性會影響編譯和執行時功能

註釋

  A:就是對程式碼的解釋和說明,其目的是讓人們能夠更加輕鬆地瞭解程式碼。註釋是編寫程式時,寫程式的人給一個語句、程式段、函式等的解釋或提示,能提高程式程式碼的可讀性

  B:註釋不能後期處理

 

二、自定義Attribute特性的使用

自定義Attribute特性的語法

//直接繼承Attribute
public class CustomAttribute : Attribute
{
    
public string Name { get; set; } public CustomAttribute() { Console.WriteLine($"{this.GetType().Name} 無參建構函式"); } public CustomAttribute(string name) { Console.WriteLine($"{this.GetType().Name} string 引數建構函式"); Name = name; } } //間接繼承Attribute public class
CustomAttributeChild : CustomAttribute { public CustomAttributeChild() { Console.WriteLine($"{this.GetType().Name} 無參建構函式"); } public CustomAttributeChild(string name) : base(name) { Console.WriteLine($"{this.GetType().Name} string 引數建構函式"); } }