[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。