使用TypeDescriptor给类动态添加Attribute

原文出处:www.cnblogs.com/bicker/p/3326763.html

给类动态添加Attribute一直是我想要解决的问题,从msdn里找了很久,到Stack Overflow看了不少文章,算是最终有了答案。

先是有这样的一段解释

Attributes are static metadata. Assemblies, modules, types, members, parameters, and return values aren't first-class objects in C# (e.g., the System.Type class is merely a reflected representation of a type). You can get an instance of an attribute for a type and change the properties if they're writable but that won't affect the attribute as it is applied to the type.

从这里看,想要实现动态添加Attribute就是不可能做到的。哈哈,被标题坑了吧。

好吧,但是我还是找到了一个东西System.ComponentModel.TypeDescriptor,这个号称可以添加Attribute到类、对象中去的类。TypeDescriptor里有方法:AddAttributes,可以把Attribute添加到类上。但是只有一个问题,添加上去的Attribute,只能通过TypeDescriptor来取到。
 


/*
*    现在需要给simpleObject添加attribute
*/
TypeDescriptor.AddAttributes(typeof(targetObject), new simpleAttribute(new targetObject()));
AttributeCollection collection = TypeDescriptor.GetAttributes(typeof(targetObject));
simpleAttribute attr = ((simpleAttribute)collection[typeof(simpleAttribute)]);
if (attr != null)
{
      MessageBox.Show(attr.ToString());
}   

 

 

           
 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值