Attributes(2): Displaying attributes for a class.(显示类属性)

时间:2022-07-29 19:23:55

输出类属性

Attributes(2): Displaying attributes for a class.(显示类属性)

 

using System;

using System.Reflection;

 

namespace Attribute02

{

//用于Class和Struct类型

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]

class
Creator : Attribute

{

private
string date;

private
string name;

private
double version;

 

public Creator(string name, string date)

{

this.name = name;

this.date = date;

this.version = 0.1;

}

 

public
Double Version

{

get { return
this.version; }

set { this.version = value; }

}

 

//输出

public
void Dump()

{

Console.WriteLine("Name: {0} Date: {1} Version: {2}",

this.name, this.date, this.version);

}

}

[Creator("PSM", "2013-09-01", Version=1.0)]

class
ATestClass01

{

public ATestClass01()

{

}

}

[Creator("PSM", "2013-09-01", Version = 2.0)]

class
ATestClass02

{

public ATestClass02()

{

}

}

[Creator("PSM", "2013-09-01", Version = 3.0)]

class
ATestClass03

{

public ATestClass03()

{

}

}

 

class
Program

{

static
void Main(string[] args)

{

PrintAttributeInformation(typeof(ATestClass01));

PrintAttributeInformation(typeof(ATestClass02));

PrintAttributeInformation(typeof(ATestClass03));

Console.ReadLine();

}

 

static
void PrintAttributeInformation(Type typeName)

{

Console.WriteLine("Attributes for class {0}", typeName);

object[] attr = typeName.GetCustomAttributes(true);

foreach (object o in attr)

{

Console.WriteLine("Attribute {0}", 0);

if (o is
Creator)

{

((Creator)o).Dump();

}

}

}

}

}