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