【问题标题】:Finding all classes with a particular attribute查找具有特定属性的所有类
【发布时间】:2010-10-17 17:40:09
【问题描述】:

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

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

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

【问题讨论】:

    标签: c# .net reflection .net-3.5


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:
      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;
       }
      

      【讨论】:

      • 这正是我所需要的!谢谢!
      • 需要注意的是,这只会找到加载的程序集。如果来自程序集的代码尚未运行,则不会加载它,因此在启动应用程序时它不会找到尚未运行的程序集。请参阅stackoverflow.com/questions/383686/… 以获取所有引用的程序集。
      猜你喜欢
      • 2013-01-04
      • 1970-01-01
      • 1970-01-01
      • 2011-04-16
      • 1970-01-01
      • 2021-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多