用户自定义Attribute

今天学习了C#中的Attribute,略做总结

 

1.Attribute的本质

它的本质是一个类,能够对程序中的元素进行标注(如assembly, class, constructor, delegate, enum, event, field, interface, method, portable executable file module, parameter, property, return value, struct, 或者其他attribute.)

 

2.如何编写用户Attribute

如同编写一个类一样,例如:

// 用户宠物特征.
public class AnimalTypeAttribute : Attribute {
// 构造器.
public AnimalTypeAttribute(Animal pet) {
thePet = pet;
}
// 内部变量.
protected Animal thePet;
// 属性.
public Animal Pet {
get { return thePet; }
set { thePet = value; }
}
}


3.如何使用用户Attribute

// 对一个测试类的方法添加特征.
class AnimalTypeTestClass {
[AnimalType(Animal.Dog)]
public void DogMethod() {}

[AnimalType(Animal.Cat)]
public void CatMethod() {}

[AnimalType(Animal.Bird)]
public void BirdMethod() {}
}

4.如何让用户Attribute运用内部逻辑

class DemoClass {
static void Main(string[] args) {
AnimalTypeTestClass testClass = new AnimalTypeTestClass();
Type type = testClass.GetType();
// 利用反射,遍历这个类中的所有方法 System.Reflection
foreach(MethodInfo mInfo in type.GetMethods()) {
// 通过Attribute类内置的GetCustemAttributes()方法遍历附加在该方法上的所有Attribute.
foreach (Attribute attr in Attribute.GetCustomAttributes(mInfo)) {
// 定位目标Attribute,进行相应的逻辑操作.
if (attr.GetType() == typeof(AnimalTypeAttribute))
Console.WriteLine(
"Method {0} has a pet {1} attribute.",
mInfo.Name, ((AnimalTypeAttribute)attr).Pet);
}
}
}
}
/*
* Output:
* Method DogMethod has a pet Dog attribute.
* Method CatMethod has a pet Cat attribute.
* Method BirdMethod has a pet Bird attribute.
*/


上面这个例子是MSDN官方的例子,很好懂;
然后附一篇很适合Attribute入门的博客
最后再附一篇比较完整的例子

posted @ 2010-05-12 17:31  C.Jun  阅读(512)  评论(1编辑  收藏  举报