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);
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;