C# の機能

属性は、プログラムのアセンブリにメタデータを追加できるようにする言語構造です。
プログラムの構造情報を保持するために使用される特別なタイプのクラスです。

属性は、宣言情報を C# コード (型、メソッド、プロパティなど) に関連付ける強力な方法を提供します。
機能がプログラム エンティティに関連付けられた後、リフレクションを使用して実行時に機能情報をクエリできます

この属性の目的は、プログラム構造に関する特定のメタデータのセットをアセンブリに埋め込むようにコンパイラに指示することであり、
ほぼすべての宣言 (クラス、変数、関数など) に配置できます。

フィーチャーの本質はクラスです。
フィーチャー クラスを使用して、
クラス、メンバー変数、メンバー メソッドなどの追加情報をメタデータに追加し、さらに追加情報を追加できます。
その後、これらを取得できます。リフレクションによる追加情報

(1) カスタム機能

// 继承特性基类 Attribute                                                                                         
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] 
internal class MyCustomAttribute : Attribute                                                               
{                                                                                                          
    // 特性中的成员 一般根据需求来写                                                                                      
    public string info;                                                                                    
                                                                                                           
    public MyCustomAttribute(string info) {                                                                
        this.info = info;                                                                                  
    }                                                                                                      
                                                                                                           
    public void TestFun() {                                                                                
        Console.WriteLine("特性的方法");                                                                        
    }                                                                                                      
}                                                                                                          

(2) 機能の利用

// 基本语法:                                                      
// [特性名(参数列表)]                                                
// 本质上 就是在调用特性类的构造函数                                          
// 写在哪里?                                                      
// 类、函数、变量上一行,表示他们具有该特性信息                                     
                                                             
[MyCustom("这个是我自己写的一个用于计算的类")]                               
[MyCustom("这个是我自己写的一个用于计算的类")]                               
internal class MyClass                                       
{                                                            
    [MyCustom("这是一个成员变量")] public int value;                 
                                                             
    // [MyCustom("这是一个用于计算加法的函数")]                            
    // public void TestFun( [MyCustom("函数参数")]int a )         
    // {                                                      
                                                             
    // }                                                      
    public void TestFun(int a) { }                           
}                         

private static void Main(string[] args) {                                                       
    Console.WriteLine("特性");                                                                    
                                                                                                
    // 特性的使用                                                                               
                                                                                                
    MyClass mc = new MyClass();                                                                 
    Type    t  = mc.GetType();                                                                  
    // t = typeof(MyClass);                                                                      
    // t = Type.GetType("xxx.MyClass");                                                  
                                                                                                
    // 判断是否使用了某个特性                                                                               
    // 参数一:特性的类型                                                                                 
    // 参数二:代表是否搜索继承链(属性和事件忽略此参数)                                                                 
    if (t.IsDefined(typeof(MyCustomAttribute), false)) Console.WriteLine("该类型应用了MyCustom特性");   
                                                                                                
    // 获取Type元数据中的所有特性                                                                           
    object[] array = t.GetCustomAttributes(true);                                               
    for (int i = 0; i < array.Length; i++) {                                                    
        if (array[i] is MyCustomAttribute) {                                                    
            Console.WriteLine((array[i] as MyCustomAttribute).info);                            
            (array[i] as MyCustomAttribute).TestFun();                                          
        }                                                                                       
    }                                                                                           
                                                                                                
    TestClass tc = new TestClass();                                                             
    tc.OldSpeak("123");                                                                         
    tc.Speak();                                                                                 
                                                                                                
    tc.SpeakCaller("123123123123123");                                                          
                                                                                                
    Fun();                                                                                        
}                                                                                               

(3) カスタム機能の利用範囲を制限する

// 通过为特性类 加特性 限制其使用范围                                                                    
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = true)]
// 参数一:AttributeTargets —— 特性能够用在哪些地方                                                    
// 参数二:AllowMultiple —— 是否允许多个特性实例用在同一个目标上                                               
// 参数三:Inherited —— 特性是否能被派生类和重写成员继承                                                     
public class MyCustom2Attribute : Attribute { }                                         

(4) システム独自の機能 - 古い機能

// 过时特性                                                                                                          
// Obsolete                                                                                                      
// 用于提示用户 使用的方法等成员已经过时 建议使用新方法                                                                                   
// 一般加在函数前的特性                                                                                                    
                                                                                                                
internal class TestClass                                                                                        
{                                                                                                               
    // 参数一:调用过时方法时 提示的内容                                                                                         
    // 参数二:true-使用该方法时会报错  false-使用该方法时直接警告                                                                      
    [Obsolete("OldSpeak方法已经过时了,请使用Speak方法", false)]                                                             
    public void OldSpeak(string str) {                                                                          
        Console.WriteLine(str);                                                                                 
    }                                                                                                           
                                                                                                                
    public void Speak() { }                                                                                                 
}                                                                                                               

(5) システム独自の機能 ~発信者情報機能~

// 哪个文件调用?                                         
// CallerFilePath特性                                
// 哪一行调用?                                          
// CallerLineNumber特性                              
// 哪个函数调用?                                         
// CallerMemberName特性                              

// 需要引用命名空间 using System.Runtime.CompilerServices; 
// 一般作为函数参数的特性                       
public void SpeakCaller(string                 str,      [CallerFilePath]   string fileName = "",           
                        [CallerLineNumber] int line = 0, [CallerMemberName] string target   = "") {         
    Console.WriteLine(str);                                                                                 
    Console.WriteLine(fileName);                                                                            
    Console.WriteLine(line);                                                                                
    Console.WriteLine(target);                                                                              
}  

(6) システム独自の機能 - 条件付きコンパイル機能

// 条件编译特性                            
// Conditional                       
// 它会和预处理指令 #define配合使用              
                                    
// 需要引用命名空间using System.Diagnostics; 
// 主要可以用在一些调试代码上                     
// 有时想执行有时不想执行的代码                    

(7) システム独自の機能 - 外部 DLL パッケージ機能の機能

// DllImport                                       
                                                  
// 用来标记非.Net(C#)的函数,表明该函数在一个外部的DLL中定义。             
// 一般用来调用 C或者C++的Dll包写好的方法                         
// 需要引用命名空间 using System.Runtime.InteropServices

おすすめ

転載: blog.csdn.net/weixin_53163894/article/details/131459242