c# – 扫描自定义属性的所有类和方法的最佳实践
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 扫描自定义属性的所有类和方法的最佳实践,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2033字,纯文字阅读大概需要3分钟。
内容图文
![c# – 扫描自定义属性的所有类和方法的最佳实践](/upload/InfoBanner/zyjiaocheng/823/89cb941d028a40b891a0412dd1435810.jpg)
我有史以来第一次真正需要手动进行装配扫描.我遇到了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();
我是否应该尝试将这两个结合起来在一次扫描中完成此操作,还是只是落入早期优化? (扫描只在app开始时执行)
是否存在一些不同的方法,这些方法对于方法的扫描更为理想,因为组件中的方法多于类型?
解决方法:
反思很慢……
我想你已经去了那里的基础知识.我建议您稍微更改一下代码,以避免进行额外的全面扫描.
如果您不止一次这样做,我还建议您考虑在任何适当的时间段内缓存结果.
像这样的伪代码Sorta:
... (optional caches) ...
IDictionary<Type, IEnumerable<Attributes>> typeAttributeCache = new ...
IDictionary<MethodInfo, IEnumerable<Attributes>> methodAttributeCache = new ...
... (in another method or class) ...
foreach assembly in GetAssemblies()
foreach type in assembly.GetTypes()
typeAttributes = typeAttributeCache.TryGet(...) // you know the correct syntax, trying to be brief
if (typeAttributes is null)
typeAttributes = type.GetCustomAttributes().OfType<TypeImLookingFor>();
typeAttributeCache[type] = typeAttributes;
foreach methodInfo in type.GetMethods()
methodAttributes = methodAttributeCache.TryGet(...) // same as above
if (methodAttributes is null)
methodAttributes = methodInfo.GetCustomAttributes().OfType<TypeImLookingFor>();
methodAttributeCache[type] = methodAttributes;
// do what you need to do
内容总结
以上是互联网集市为您收集整理的c# – 扫描自定义属性的所有类和方法的最佳实践全部内容,希望文章能够帮你解决c# – 扫描自定义属性的所有类和方法的最佳实践所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。