c# 反射动态添加Attribute

//测试类
var type = typeof(TestClass);


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

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

//给Property添加、获取特性
var propertyInfo = type.GetProperty("Class1Obj");
TypeDescriptor.AddAttributes(propertyInfo, indexAttr);
//var attr = TypeDescriptor.GetAttributes(propertyInfo)[typeof(DynamicCacheBufferAtrribute)] as DynamicCacheBufferAtrribute;

[参考]
C# - 反射动态添加/删除Attribute特性

posted @ 2025-09-22 17:50  Hey,Coder!  阅读(6)  评论(0)    收藏  举报