简体   繁体   English

查找具有特定属性的所有类

[英]Finding all classes with a particular attribute

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.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).我正在查看AppDomain.CurrentDomain但我对它不太熟悉,并且不确定需要如何提升 privlages(如果可能,我希望能够在 Web 应用程序中以最小的信任运行库,但越低相信我会更快乐)。 I also want to keep performance in mind (it's a .NET 3.5 library so LINQ is completely valid!).我还想牢记性能(它是一个 .NET 3.5 库,所以 LINQ 是完全有效的!)。

So is AppDomain.CurrentDomain my best/ only option and then just looping through all the assemblies, and then types in those assemblies?那么AppDomain.CurrentDomain是我最好的/唯一的选择,然后循环遍历所有程序集,然后输入这些程序集吗? 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;
 }

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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM