C# 查找具有特定属性的所有类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/720157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding all classes with a particular attribute
提问by Aaron Powell
I've got a .NET library in which I need to find all the classes which have a custom attribute I've defined on them, and I want to be able to find them on-the-fly when an application is using my library (ie - I don't want a config file somewhere which I state the assembly to look in and/ or the class names).
我有一个 .NET 库,我需要在其中找到所有具有自定义属性的类,我希望能够在应用程序使用我的库时即时找到它们(即 - 我不希望在某处有一个配置文件,我声明程序集要查看和/或类名)。
I was looking at AppDomain.CurrentDomainbut I'm not overly familiar with it and not sure how elivated the privlages need to be (I want to be able to run the library in a Web App with minimal trust if possible, but the lower the trust the happier I'd be). I also want to keep performance in mind (it's a .NET 3.5 library so LINQ is completely valid!).
我正在查看,AppDomain.CurrentDomain但我对它并不太熟悉,并且不确定需要如何提升隐私(如果可能,我希望能够以最小的信任在 Web 应用程序中运行库,但信任越低越快乐我会成为)。我还想牢记性能(它是一个 .NET 3.5 库,所以 LINQ 是完全有效的!)。
So is AppDomain.CurrentDomainmy best/ only option and then just looping through all the assemblies, and then types in those assemblies? Or is there another way
那么AppDomain.CurrentDomain我最好/唯一的选择是循环遍历所有程序集,然后输入这些程序集吗?或者还有其他方法
采纳答案by Mark Cidade
IEnumerable<Type> GetTypesWith<TAttribute>(bool inherit)
where TAttribute: System.Attribute
{ return from a in AppDomain.CurrentDomain.GetAssemblies()
from t in a.GetTypes()
where t.IsDefined(typeof(TAttribute),inherit)
select t;
}
回答by Roger Hill
Mark posted a good answer, but here is a linq free version if you prefer it:
马克发布了一个很好的答案,但如果您愿意,这里有一个 linq 免费版本:
public static IEnumerable<Type> GetTypesWith<TAttribute>(bool inherit) where TAttribute : Attribute
{
var output = new List<Type>();
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (var assembly in assemblies)
{
var assembly_types = assembly.GetTypes();
foreach (var type in assembly_types)
{
if (type.IsDefined(typeof(TAttribute), inherit))
output.Add(type);
}
}
return output;
}

