using System;
using System.Reflection;
namespace AttributeTest
{
class Program
{
static void Main(string[] args)
{
AnimalTypeTestClass testClass = new AnimalTypeTestClass();
Type type = testClass.GetType();
// 遍历类中的所有字段
foreach (FieldInfo fInfo in type.GetFields())
{
// 遍历字段上绑定的所有特性
foreach (Attribute attr in Attribute.GetCustomAttributes(fInfo))
{
if (attr.GetType() == typeof(AnimalTypeAttribute))
Console.WriteLine(
"Field Name={0} Description={1} attribute.",
fInfo.Name, ((AnimalTypeAttribute)attr).Description);
}
}
Console.ReadKey();
}
}
public class AnimalTypeAttribute : Attribute
{
protected string _description;
public AnimalTypeAttribute(string description)
{
_description = description;
}
public string Description
{
get
{
return _description;
}
}
}
class AnimalTypeTestClass
{
[AnimalType("名字")]
public string Name;
[AnimalType("年龄")]
public string Year;
}
}
运行效果