用户自定义Attribute

本文介绍了C#中的Attribute特性,包括其本质、如何编写和使用自定义Attribute,以及如何在Attribute中实现内部逻辑。通过示例代码展示了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入门的博客
最后再附一篇比较完整的例子

转载于:https://www.cnblogs.com/chenjunsheep/archive/2010/05/12/1733870.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值