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

Aar*_*ell 31 .net c# reflection .net-3.5

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

我在看,AppDomain.CurrentDomain但我并不过分熟悉它,并且不确定这些权限需要多少(我希望能够以尽可能少的信任在Web应用程序中运行库,但信任度越低越快乐我会).我还想记住性能(这是一个.NET 3.5库,所以LINQ完全有效!).

那么这是AppDomain.CurrentDomain我最好/唯一的选择,然后循环遍历所有程序集,然后键入这些程序集?还是有另一种方式

Mar*_*ade 81

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;
 }
Run Code Online (Sandbox Code Playgroud)

  • 应该注意的是,这只会找到加载的程序集。如果程序集中的代码尚未运行,则不会加载它,因此在应用程序启动时,它将找不到尚未运行的程序集。请参阅 /sf/ask/26858051/#26300241 以获取所有引用的程序集。 (2认同)