在.NET中,GetCustomAttributes()
方法每次调用时创建新的属性实例的行为是由其设计机制决定的,以下是详细解析:
System.Attribute
。GetCustomAttributes()
:反射API中用于检索目标元素上的自定义属性集合的方法,返回一个对象数组。AttributeBuilder
),新实例可能包含运行时计算的逻辑。RuntimeType
或RuntimeMethodInfo
等内部类型动态实例化属性,每次调用均触发属性构造函数。var attributes = typeof(MyClass).GetCustomAttributes(typeof(MyAttribute), false);
// 缓存到静态变量中重复使用
private static readonly object[] _cachedAttributes = attributes;
Attribute.GetCustomAttribute()
若只需单个属性实例,此方法可能更高效:
var attribute = Attribute.GetCustomAttribute(
typeof(MyClass),
typeof(MyAttribute)
);
GetCustomAttributes()
。TypeDescriptor
(如对组件模型场景):TypeDescriptor
(如对组件模型场景):foreach (var item in items)
{
var attrs = item.GetType().GetCustomAttributes(); // 每次创建新实例
}
var attributeCache = new Dictionary<Type, IEnumerable<Attribute>>();
foreach (var item in items)
{
if (!attributeCache.TryGetValue(item.GetType(), out var attrs))
{
attrs = item.GetType().GetCustomAttributes().Cast<Attribute>().ToArray();
attributeCache[item.GetType()] = attrs;
}
// 使用缓存的attrs
}
.NET选择每次创建新属性实例是为了保证安全性和灵活性,开发者可通过缓存或替代API优化性能。根据场景选择合适策略即可。
没有搜到相关的文章