【发布时间】:2025-11-26 17:35:01
【问题描述】:
我第一次真正需要自己手动进行装配扫描。我遇到了C# - how enumerate all classes with custom class attribute?,这让我很兴奋
var typesWithMyAttribute =
(from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
let attributes = type.GetCustomAttributes(typeof(SomeAttribute), true)
where attributes != null && attributes.Length > 0
select new { Type = type, Attributes = attributes.Cast<SomeAttribute>() })
.ToList();
这很简单,可以扩展到方法级别
var methodsWithAttributes =
(from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
from method in type.GetMethods()
let attributes = method.GetCustomAttributes(typeof(SomeAttribute), true)
where attributes != null && attributes.Length > 0
select new { Type = type, Method = method,
Attributes = attributes.Cast<SomeAttribute>() })
.ToList();
我应该尝试将这 2 项结合起来在一次扫描中执行此操作,还是只是属于早期优化? (扫描只会在应用启动时执行)
由于方法比程序集中的类型多得多,有什么不同的方法可以更好地扫描方法吗?
【问题讨论】:
-
我敢打赌,枚举程序集和类型将比查找和实例化属性快得多,因此缓存程序集和类型将毫无意义。
标签: c# reflection performance