发现的所有类具有特定属性 [英] Finding all classes with a particular attribute

查看:254
本文介绍了发现的所有类具有特定属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.net库中,我需要找到所有具有自定义属性我对他们所定义的类,并且我希望能够找到它们的即时当应用程序是使用我的图书馆(即 - 我不想要一个配置文件的地方,我状态大会看在和/或类名)

我在看 AppDomain.CurrentDomain 但我不是太熟悉它,不知道如何elivated的privlages需要是(我想能够运行该库在Web应用程序以最小信任的如果可能的话的,但较低的信任的幸福,我会)。我也想保持业绩记住(这是一个.NET 3.5库,以便LINQ是完全有效的!)。

那么, AppDomain.CurrentDomain 我最好的/唯一的选择,然后就通过所有的组件循环,然后类型的组件?或者是有另一种方式

解决方案

 的IEnumerable<类型> GetTypesWith< TAttribute>(布尔继承)
                              其中,TAttribute:System.Attribute
 {从在AppDomain.CurrentDomain.GetAssemblies返回()
          从吨a.GetTypes()
          其中,t.IsDefined(typeof运算(TAttribute),继承)
          选择吨;
 }
 

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).

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!).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆