查找具有特定属性的所有类 [英] Finding all classes with a particular attribute
问题描述
我有一个 .NET 库,我需要在其中找到所有具有我定义的自定义属性的类,并且我希望能够在应用程序运行时即时找到它们使用我的库(即 - 我不希望在某处使用配置文件来声明要查看的程序集和/或类名).
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).
我正在查看 AppDomain.CurrentDomain
但我对它并不太熟悉,并且不确定需要如何提升权限(我希望能够在 Web 应用程序中运行该库如果可能,信任度最低,但信任度越低,我越开心).我还想牢记性能(它是一个 .NET 3.5 库,因此 LINQ 完全有效!).
I was looking at AppDomain.CurrentDomain
but 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
是我最好/唯一的选择,然后循环遍历所有程序集,然后输入这些程序集吗?或者还有别的方法
So is AppDomain.CurrentDomain
my best/ only option and then just looping through all the assemblies, and then types in those assemblies? Or is there another way
推荐答案
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;
}
这篇关于查找具有特定属性的所有类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!