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

问题描述 投票:0回答:2

我有一个 .NET 库,我需要在其中查找具有我定义的自定义属性的所有类,并且我希望能够在应用程序使用我的库(即 - 我不需要一个配置文件来声明要查找的程序集和/或类名称)。

我正在查看

AppDomain.CurrentDomain
,但我对它不太熟悉,并且不确定需要如何提升权限(我希望能够以最小的信任度在Web应用程序中运行该库如果可能的话,但是信任度越低,我就越快乐)。我还想牢记性能(它是一个 .NET 3.5 库,因此 LINQ 完全有效!)。

那么

AppDomain.CurrentDomain
是我最好/唯一的选择,然后循环遍历所有程序集,然后输入这些程序集吗?或者还有其他方法吗

c# .net reflection .net-3.5
2个回答
85
投票
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;
 }

4
投票

Mark 发布了一个很好的答案,但如果您愿意,这里有一个 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;
    }

我喜欢这个而不是使用 linq 的答案,因为它更容易调试和单步执行。它还非常适合每个步骤中更复杂的逻辑。

我认为 Linq 对于简单的事情来说非常棒,但随着过滤/转换的复杂性增加,维护起来会变得非常困难。

© www.soinside.com 2019 - 2024. All rights reserved.