首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> C# 入門

C# 反射機制詳解:Type/MemberInfo/Attribute/動態創建實例

     編輯:C# 入門

C# 反射機制詳解:Type/MemberInfo/Attribute/動態創建實例

反射讓程序在運行時檢查、修改自身結構與行為。核心命名空間 System.Reflection,核心類型 Type。

優缺點權衡

優點缺點
極高靈活性、擴展性、解耦性能顯著低於直接調用(解釋操作)
無需硬編碼目標類型模糊程序邏輯,維護困難,代碼複雜
框架級開發必備(DI、ORM、序列化)普通業務代碼不建議使用

核心用途

  • 運行時查看 Attribute 元數據
  • 審查程序集類型、動態實例化
  • 延遲綁定調用方法/屬性
  • 運行時發射新類型 (System.Reflection.Emit)

查看自定義 Attribute 示例

[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : Attribute {
    public string Url { get; }
    public string Topic { get; set; }
    public HelpAttribute(string url) => Url = url;
}
[HelpAttribute("Info", Topic="Class")]
class MyClass {}
// 反射讀取
var info = typeof(MyClass);
var attrs = info.GetCustomAttributes(true);
foreach (var a in attrs) Console.WriteLine(a);  // HelpAttribute

完整實戰:Bug 追蹤屬性掃描

[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method, AllowMultiple=true)]
public class DeBugInfo : Attribute {
    public int BugNo { get; }
    public string Developer { get; }
    public string LastReview { get; }
    public string Message { get; set; }
    public DeBugInfo(int no, string dev, string review) { ... }
}
[DeBugInfo(45, "Zara", "12/8/2012", Message="Return mismatch")]
class Rectangle { ... }
// 掃描類與方法屬性
var type = typeof(Rectangle);
foreach (var attr in type.GetCustomAttributes(false)) { ... }
foreach (var method in type.GetMethods()) {
    foreach (var attr in method.GetCustomAttributes(true)) { ... }
}

輸出包含類級、方法級所有 DeBugInfo 記錄。

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