【问题标题】:How to get the classes that implement an interface in CodeRush?如何在 CodeRush 中获取实现接口的类?
【发布时间】:2026-01-15 01:35:01
【问题描述】:

我试图编写一个返回实现接口的类列表的方法,但无法做到。

类似的方法

  public List<Class> GetImplementedClasses(Interface Interface1)
   {
        . . . 
   }

我尝试使用 interface1.AllChildren 和许多其他尝试。他们都没有给出任何结果。

是否可以使用 DXCore API 编写这样的方法?

示例:

如果我通过 Interface1,我应该从方法 GetImplementedClasses 中获取 Class1 和 Class2。

提前致谢。

【问题讨论】:

    标签: coderush dxcore


    【解决方案1】:

    Interface 类中有一个“GetDescendants”方法可能对您的任务有用。代码将如下所示:

    public List<Class> GetImplementedClasses(Interface Interface1)
    {
      List<Class> result = new List<Class>();
      if (Interface1 != null)
      {
        ITypeElement[] descendants = Interface1.GetDescendants();
        foreach (ITypeElement descendant in descendants)
        {
          if (!descendant.InReferencedAssembly)
          {
            Class classDescendant = descendant.ToLanguageElement() as Class;
            if (classDescendant != null)
              result.Add(classDescendant);
          }
        }
      }
      return result;
    }
    

    【讨论】:

    • 感谢您的回答.. 但这不起作用 ...ITypeElement[] descendants = Interface1.GetDescendants();在这一行中 Interface1.GetDescendants() 返回 null..
    • 奇怪,我创建了一个测试插件,它显示了一个接口的所有实现者,它按预期工作。如何检索接口的实例?您可以从此链接下载测试插件和测试代码(根据您的示例):downloads.devexpress.com/Share/Temp/TestPlugIn/…
    • 这不起作用。我用 CodeRushXpress-10.2.6 和 CodeRushXpress-11.1.4 试过这个。我也在console app outside visual studio 中尝试过这个,对后代的手表显示为空。
    • @Sachin,您能否分享您的插件以供调查?您可以通过“support@devexpress.com”联系 DevExpress 支持服务,他们将很乐意为您提供帮助。
    • 是的,试试这个: DescendantReferencesSearcher searcher = new DescendantReferencesSearcher(ParserServices.SourceTreeResolver); IElementCollection 后代 = searcher.Search(interface1.Solution, type);
    【解决方案2】:

    我不确定 dxcore,但在常规 C# 中,我编写了 an extension method,它可以获取部署中可用的所有类型;你可以这样使用它:

    Assembly.GetExecutingAssembly().GetAvailableTypes(
        typeFilter: t => 
            (t != typeof(interfaceType)) 
            && 
            typeof(interfaceType).IsAssignableFrom(t));
    

    【讨论】:

    • 我正在尝试为 Visual Studio 编写一些简单的插件,因此使用 CodeRush API 回答更接近这个问题 ....:)