C# - 反射动态添加/删除Attribute特性
API:TypeDescriptor.AddAttributesTypeDescriptor.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).OfTypeDynamicCacheBufferAtrribute().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)).OfTypeDynamicCacheBufferAtrribute().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;