Retrieve Attribute by using reflection : Attributes Reflection « Attribute « C# / CSharp Tutorial






using System;  
using System.Reflection; 
  
[AttributeUsage(AttributeTargets.All)] 
public class MyAttribute : Attribute { 
  public string remark; 
 
  public MyAttribute(string comment) { 
    remark = comment; 
  } 
 
  public string Remark { 
    get { 
      return remark; 
    } 
  } 
}  
 
[MyAttribute("This class uses an attribute.")] 
class UseAttrib { 
} 
 
class MainClass {  
  public static void Main() {  
    Type t = typeof(UseAttrib); 
 
    Console.Write("Attributes in " + t.Name + ": "); 
 
    object[] attribs = t.GetCustomAttributes(false);  
    foreach(object o in attribs) { 
      Console.WriteLine(o); 
    } 
 
    Console.Write("Remark: "); 
 
    // Retrieve the MyAttribute. 
    Type tRemAtt = typeof(MyAttribute); 
    MyAttribute ra = (MyAttribute) 
          Attribute.GetCustomAttribute(t, tRemAtt); 
 
    Console.WriteLine(ra.remark); 
  }  
}
Attributes in UseAttrib: MyAttribute
Remark: This class uses an attribute.








10.5.Attributes Reflection
10.5.1.Reflecting on Attributes
10.5.2.Retrieve Attribute by using reflection
10.5.3.Use Reflection to get the Attribute
10.5.4.Use the GetCustomAttributes method
10.5.5.Load class method by Attribute