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

開發故事(四):運用反射在執行時動態讀取自訂 Attribute 資訊

     編輯:關於ASP.NET

自訂 Attribute

[AttributeUsage(AttributeTargets.Class, Inherited=false, AllowMultiple=false)]
public sealed class TextAttribute : Attribute {
    private readonly string _text;
    public TextAttribute(string text) { _text = text; }
    public string Text { get { return _text; } }
}

標記目標類別

[Text("Hello, Anytao")]
public class Hello { }

反射讀取

Type t = typeof(Hello);
object[] attrs = t.GetCustomAttributes(typeof(TextAttribute), false);
if (attrs.Length > 0) {
    TextAttribute ta = (TextAttribute)attrs[0];
    Console.WriteLine(ta.Text); // 輸出 Hello, Anytao
}

同理可針對 MethodInfo、PropertyInfo、FieldInfo、ParameterInfo 讀取對應 Attribute。

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