首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

[你必須知道的.NET] 第三回:Attribute 特性與 Property 屬性深度解析(三):自訂特性完整範例、反射取得、MSDN 定義、結論

     編輯:關於C語言

五、經典範例:自訂特性完整實作

using System;
using System.Reflection;

namespace Anytao.Net
{
    // 特性應用於特性:控制自訂特性如何被應用
    [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
    public class MyselfAttribute : Attribute
    {
        private string _name;
        private int _age;
        private string _memo;
        
        public MyselfAttribute() { }
        public MyselfAttribute(string name, int age) { _name = name; _age = age; }
        
        // 特性的屬性(注意:特性 ≠ 屬性)
        public string Name { get { return _name ?? string.Empty; } }
        public int Age { get { return _age; } }
        public string Memo { get { return _memo; } set { _memo = value; } }
        
        public void ShowName() => Console.WriteLine("Hello, {0}", _name ?? "world.");
    }
    
    // 應用自訂特性:可用 Myself 或 MyselfAttribute,可設定屬性 Memo
    [Myself("Emma", 25, Memo = "Emma is my good girl.")]
    public class MyTest
    {
        public void SayHello() => Console.WriteLine("Hello, my .Net world.");
    }
    
    public class MyRun
    {
        public static void Main()
        {
            // 反射取得特性資訊
            Type tp = typeof(MyTest);
            MemberInfo info = tp;
            
            MyselfAttribute attr = (MyselfAttribute)Attribute.GetCustomAttribute(info, typeof(MyselfAttribute));
            
            if (attr != null)
            {
                Console.WriteLine("Name: {0}", attr.Name);
                Console.WriteLine("Age: {0}", attr.Age);
                Console.WriteLine("Memo of {0} is {1}", attr.Name, attr.Memo);
                attr.ShowName(); // Hello, Emma
            }
            
            // 反射建立實例並呼叫方法
            object obj = Activator.CreateInstance(typeof(MyTest));
            MethodInfo mi = tp.GetMethod("SayHello");
            mi.Invoke(obj, null); // Hello, my .Net world.
            
            Console.ReadLine();
        }
    }
}

六、他山之石:相關資源推薦

  • MSDN 定義:特性描述序列化、安全性、JIT 優化限制、偵錯資訊、文件作者、設計時控制項可見性
  • dudu 系列:《Attribute 在 .Net 編程中的應用》
  • 亞歷山大系列:《手把手教你寫 ORM (六)》
  • idior 文章:《Remoting 基本原理及其擴展機制》

七、結論

Attribute 是 .NET 引入的標誌性技術:

  1. 本質是類別,繼承 System.Attribute
  2. 編譯期初始化,執行期以反射取得附加資訊
  3. 核心應用:序列化控制、安全性需求、編譯器指令、設計模式標記、除錯優化、非受控函數標記、過時標記、條件編譯
  4. 命名慣例:類別名以 Attribute 結尾,使用時可省略

深入掌握 Attribute,能解鎖 .NET 元程式設計、AOP、框架開發的核心能力。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved