是否可以获取应用了自定义属性的所有引用程序集(在单元测试项目中)。我在成功运行的应用程序中使用了以下代码:
var assemblies = System.Web.Compilation.BuildManager.GetReferencedAssemblies().Cast<Assembly>().Where(a => a.GetCustomAttributes(false).OfType<AssemblyCategoryAttribute>().Any()).ToList();
但是 System.Web.Compilation.BuildManager 在我的测试项目中不起作用,所以我尝试了:
Assembly.GetExecutingAssembly().GetReferencedAssemblies().Select(a => Assembly.ReflectionOnlyLoad(a.FullName).Where(a => a.GetCustomAttributes(false).OfType<AssemblyCategoryAttribute>().Any()).ToList();
但这引发了错误:
It is illegal to reflect on the custom attributes of a Type loaded via ReflectionOnlyGetType (see Assembly.ReflectionOnly) -- use CustomAttributeData instead.
如果有人能告诉我如何做到这一点,我将不胜感激。谢谢
最佳答案
由于您正在获取当前正在执行的程序集的引用程序集,因此没有理由进行仅反射加载。 ReflectionOnlyLoad
适用于您想要查看程序集但不实际执行它们的情况。由于这些程序集正在被当前正在执行的程序集引用,因此很可能无论如何都将加载到执行上下文中。
试着做:
Assembly
.GetExecutingAssembly()
.GetReferencedAssemblies()
.Select(a => Assembly.Load(a.FullName))
.Where(a => a.
.GetCustomAttributes(false)
.OfType<AssemblyCategoryAttribute>()
.Any())
.ToList();
或者更好的是:
Assembly
.GetExecutingAssembly()
.GetReferencedAssemblies()
.Select(Assembly.Load)
.Where(a => a.IsDefined(typeof(AssemblyCategoryAttribute), false))
.ToList();
关于c# - 在单元测试项目中获取具有属性的程序集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12734724/