A simple attribute example
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.All)]
class RemarkAttribute : Attribute {
string remarkValue;
public RemarkAttribute(string comment) {
remarkValue = comment;
}
public string remark {
get {
return remarkValue;
}
}
}
[RemarkAttribute("This class uses an attribute.")]
class UseAttrib {
// ...
}
public class AttribDemo {
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 RemarkAttribute.
Type tRemAtt = typeof(RemarkAttribute);
RemarkAttribute ra = (RemarkAttribute)
Attribute.GetCustomAttribute(t, tRemAtt);
Console.WriteLine(ra.remark);
}
}
Related examples in the same category