Mega Code Archive

 
Categories / C# Tutorial / Attribute
 

Retrieve Attribute by using reflection

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.