【问题标题】:How to find a type by FQN in a solution?如何在解决方案中通过 FQN 查找类型?
【发布时间】:2021-06-26 21:08:51
【问题描述】:

我正在编写一个 Rider/ReSharper nav-from-here 插件,它应该使用一些简单的规则根据我所站立的符号确定目标类型,最后导航到它。

第一部分还可以,我已经设法形成了所需的 FQN,但我在导航方面遇到了困难。我找到了this StackOverflow 帖子,并认为我可以尝试这种方法。所以我一直在尝试使用TypeFactory.CreateTypeByCLRName 两个小时来创建一个IDeclaredType 实例,以便能够使用GetTypeElement() 获取IDeclaredElement 并最终获得它的声明。但是 API 似乎发生了变化,无论我做什么,我的代码都无法正常工作。

这是我目前得到的:

// does not work with Modules.GetModules(), either
foreach (var psiModule in solution.GetPsiServices().Modules.GetSourceModules())
{
    var type = TypeFactory.CreateTypeByCLRName("MyNamespace.MyClassName", psiModule);
    var typeElement = type.GetTypeElement();

    if (typeElement != null)
    {
        MessageBox.ShowInfo(psiModule.Name); // to make sure sth is happening
        break;
    }
}

奇怪的是,我实际上看到了一个消息框——但只有当带有MyClassName.cs 的选项卡处于活动状态时。当它处于焦点时,一切都很好。如果不是或文件已关闭,则无法解析该类,type.IsResolvedfalse

我做错了什么?

【问题讨论】:

    标签: c# resharper rider resharper-plugins


    【解决方案1】:

    为此,您应该在计划使用您正在寻找的类型的上下文中拥有一个 IPsiModule 实例。您可以通过.GetPsiModule() 方法或许多其他方式(如dataContext.GetData(PsiDataConstants.SOURCE_FILE)?.GetPsiModule())从您正在使用的某个语法节点获取它。

    void FindTypes(string fullTypeName, IPsiModule psiModule)
    {
      // access the symbol cache where all the solution types are stored
      var symbolCache = psiModule.GetPsiServices().Symbols;
    
      // get a view on that cache from specific IPsiModule, include all referenced assemblies
      var symbolScope = symbolCache.GetSymbolScope(psiModule, withReferences: true, caseSensitive: true);
    
      // or use this to search through all of the solution types
      // var symbolScope = symbolCache.GetSymbolScope(LibrarySymbolScope.FULL, caseSensitive: true);
    
      // request all the type symbols with the specified full type name
      foreach (var typeElement in symbolScope.GetTypeElementsByCLRName(fullTypeName))
      {
        // ...
      }
    }
    

    【讨论】:

    • 谢谢,它有效!但是,天哪,我什至没有接近解决方案! :) 想指出我没有直接引用目标项目,所以只有LibrarySymbolScope.FULL 的第二种方法对我有用。
    猜你喜欢
    • 2015-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2019-12-21
    • 2015-04-16
    相关资源
    最近更新 更多