是否可以获取应用自定义属性的所有引用程序集(在单元测试项目中)。我使用以下代码成功地运行了我的应用程序:
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();但这却造成了错误:
对通过ReflectionOnlyGetType加载的Type的自定义属性进行反思是非法的(参见Assembly.ReflectionOnly) --使用CustomAttributeData代替。
如果有人能教我怎么做,我会很感激的。谢谢
发布于 2012-10-04 20:12:10
由于您正在获取当前正在执行的程序集的引用程序集,因此没有理由只加载反射。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();发布于 2012-10-04 19:48:44
看看CustomAttributeData Class
为加载到仅反射上下文的程序集、模块、类型、成员和参数提供对自定义属性数据的访问。
这里有一个示例c#代码
public static void Main()
{
Assembly asm = Assembly.ReflectionOnlyLoad("Source");
Type t = asm.GetType("Test");
MethodInfo m = t.GetMethod("TestMethod");
ParameterInfo[] p = m.GetParameters();
Console.WriteLine("\r\nAttributes for assembly: '{0}'", asm);
ShowAttributeData(CustomAttributeData.GetCustomAttributes(asm));
Console.WriteLine("\r\nAttributes for type: '{0}'", t);
ShowAttributeData(CustomAttributeData.GetCustomAttributes(t));
Console.WriteLine("\r\nAttributes for member: '{0}'", m);
ShowAttributeData(CustomAttributeData.GetCustomAttributes(m));
Console.WriteLine("\r\nAttributes for parameter: '{0}'", p);
ShowAttributeData(CustomAttributeData.GetCustomAttributes(p[0]));
}在您的例子中,类似这样的情况(没有亲自尝试代码):
var assemblies = Assembly.GetExecutingAssembly()
.GetReferencedAssemblies()
.Select(a => Assembly.ReflectionOnlyLoad(a.FullName))
.Select(a => new
{ Asm = a,
CustomAttributeDataList = CustomAttributeData.GetCustomAttributes(a)
})
.Where(x => x.CustomAttributeDataList.Any(y => y.AttributeType ==
type(AssemblyCategoryAttribute)))
.Select(x => x.Asm)
.ToList();https://stackoverflow.com/questions/12734724
复制相似问题