Displaying attributes for a class.
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class Creator : System.Attribute {
public Creator(string name, string date) {
this.name = name;
this.date = date;
version = 0.1;
}
public void Dump() {
Console.WriteLine("Name {0}", name);
Console.WriteLine("Date {0}", date);
Console.WriteLine("Version {0}", version);
}
string date;
string name;
public double version;
}
[Creator("A", "01/01/2008", version = 1.1)]
class ATestClass1 {
ATestClass1() {
}
}
[Creator("B", "04/01/2008", version = 1.5)]
class ATestClass2 {
ATestClass2() {
}
}
[Creator("C", "12/31/2008", version = 2.5)]
class ATestClass3 {
ATestClass3() {
}
}
class MainClass {
public static void PrintAttributeInformation(Type classType) {
Console.WriteLine("Attributes for class {0}", classType);
object[] attr = classType.GetCustomAttributes(true);
foreach (object o in attr) {
Console.WriteLine("Attribute {0}", o);
if (o is Creator)
((Creator)o).Dump();
}
}
public static void Main() {
PrintAttributeInformation(typeof(ATestClass1));
PrintAttributeInformation(typeof(ATestClass2));
PrintAttributeInformation(typeof(ATestClass3));
}
}
Related examples in the same category