C# - 反射动态添加/删除Attribute特性

API: 

TypeDescriptor.AddAttributes

TypeDescriptor.GetAttributes

注意:TypeDescriptor.AddAttributes添加的特性需要使用 TypeDescriptor.GetAttributes获取

根据api可以看到,该接口不仅可以给指定类(Type)添加特性,还能给其他任意object类型对象添加特性

添加:
public class DynamicCacheBufferAtrribute : Attribute
{
	public int Value;
    public DynamicCacheBufferAtrribute(int v)
    {
        Value = v;
    }
}
public class MyClass1
{
    
}
public class MyClass2
{
    public MyClass1 Class1Obj;
}

//需要添加的特性集
var attributes = new Attribute[]
{
	new DynamicCacheBufferAtrribute(123)
};


//给 MyClass1 类型添加、获取特性
TypeDescriptor.AddAttributes(typeof(MyClass1), attributes);
var attr = TypeDescriptor.GetAttributes(typeof(MyClass1))[typeof(DynamicCacheBufferAtrribute)] as DynamicCacheBufferAtrribute;
//var attr = TypeDescriptor.GetAttributes(field).OfType<DynamicCacheBufferAtrribute>().FirstOrDefault();


//给类对象添加、获取特性
var class1Inst = new MyClass1(); 
TypeDescriptor.AddAttributes(class1Inst , attributes);
var attr = TypeDescriptor.GetAttributes(class1Inst)[typeof(DynamicCacheBufferAtrribute)] as DynamicCacheBufferAtrribute;


//给FieldInfo添加、获取特性
var class2Inst = new MyClass2();
class2Inst.Class1Obj = new MyClass1(); 
var fieldInfo = class2Inst.GetType().GetField("Class1Obj");
TypeDescriptor.AddAttributes(fieldInfo, attributes);
var attr = TypeDescriptor.GetAttributes(fieldInfo)[typeof(DynamicCacheBufferAtrribute)] as DynamicCacheBufferAtrribute;



//给PropertyInfo添加、获取特性
var class2Inst = new MyClass2();
class2Inst.Class1Obj = new MyClass1(); 
var propertyInfo = class2Inst.GetType().GetProperty("Class1Obj");
TypeDescriptor.AddAttributes(propertyInfo, attributes);
var attr = TypeDescriptor.GetAttributes(propertyInfo)[typeof(DynamicCacheBufferAtrribute)] as DynamicCacheBufferAtrribute;


//其他object类型均可
删除:
//清空MyClaas1类型的所有DynamicCacheBufferAtrribute特性
var attrs = TypeDescriptor.GetAttributes(typeof(MyClass1)).OfType<DynamicCacheBufferAtrribute>().ToArray();
ArrayUtility.Clear(ref attrs);
TypeDescriptor.AddAttributes(typeof(MyClass1), attrs);
附加API解释: 

TypeDescriptor.GetProperties(object)获取对象的特性

如果对象是一个属性(Property)

那么需要使用一下方式获取其特性

TypeDescriptor.GetProperties(belongClassType)[propertyName].Attributes​​​​​​​

// 假设我们有一个类和一个特性
public class MyClass
{
    [MyAttribute]
    public int MyProperty { get; set; }
}
 
public class MyAttribute : Attribute { }
 
// 获取类的特性
MyClass myClass = new MyClass();
AttributeCollection attributes = TypeDescriptor.GetAttributes(myClass);
 
// 获取属性的特性
PropertyDescriptor propertyDescriptor = TypeDescriptor.GetProperties(typeof(MyClass))["MyProperty"];
AttributeCollection propertyAttributes = propertyDescriptor.Attributes;

 

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值