如何在解决方案中通过FQN找到类型



我正在从这里编写一个Rider/ReSharper导航插件,该插件应该根据我所站的符号使用一些简单的规则来确定目标类型,并最终导航到它。

第一部分还可以,我已经设法形成了所需的FQN,但我在导航方面很吃力。我发现了这个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.IsResolved就是false

我做错了什么?

要做到这一点,您应该从计划使用所需类型的上下文中获得一个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))
{
// ...
}
}

最新更新