从 ITypeSymbol 获取 TypeSyntax [英] Get TypeSyntax from ITypeSymbol
问题描述
我正在尝试使用 Roslyn-CTP.
I'm experimenting a bit with the Roslyn-CTP.
目前我正在尝试用具体类型替换 var
.
Currently I'm trying to replace var
with the concrete type.
var i=1;
应该变成:
int i=1;
找出推断的类型很容易.但是因为这部分发生在语义模型中,所以我得到了一个 ITypeSymbol
.替换发生在语法模型中,所以我需要一个 TypeSyntax
.由于我不想要一个臃肿的名称(global::System.Int32
),转换是依赖于上下文的(using
、嵌套类型等).
Figuring out the inferred type is easy. But since this part happens in the semantic model I get a ITypeSymbol
. The replacement happens in the syntax model, so I need a TypeSyntax
. Since I don't want a bloated name (global::System.Int32
), the conversion is context dependent (using
, nested types etc.).
作为 Roslyn 一部分的 Visual Studio 版本已经在其简化类型名称"快速修复程序中具有此功能,但查看示例我找不到进行此转换的简单方法.
The Visual studio version that's part of Roslyn already has this functionality in its "Simplify type name" quickfix, but looking over the samples I couldn't find an easy way to do this conversion.
根据我现在使用的 Kevin Pilch-Bisson 的回答:
Based on Kevin Pilch-Bisson's answer I'm now using:
var location = document.GetSyntaxTree().GetLocation(node);
string name = variableType.ToMinimalDisplayString((Location)location, (SemanticModel)document.GetSemanticModel());
可以从 CommonSyntaxTree
获取 ToMinimalDisplayString
的位置.
A location which ToMinimalDisplayString
can be obtained from a CommonSyntaxTree
.
另外一个复杂性是 ToMinimalDisplayString
需要类 Location
和 SemanticModel
,而 document.GetSemanticModel()
和 CommonSyntaxTree.GetLocation
只返回一个接口.
我通过简单地投射到类来解决这个问题,这现在似乎有效.
An additional complication is that ToMinimalDisplayString
requires the classes Location
and SemanticModel
, whereas document.GetSemanticModel()
and CommonSyntaxTree.GetLocation
only return an interface.
I worked around by simply casting to the classes, which seems to work for now.
嗯,看起来类是特定于 C# 的,并且接口语言独立.
Hmm it looks like the classes are C# specific, and the interfaces language independent.
我已经在 github 上上传了一个工作版本:https://github.com/CodesInChaos/Roslyn
I've uploaded a working version on github: https://github.com/CodesInChaos/Roslyn
它不适用于 foreach
中的 var
,但我怀疑这是当前 Roslyn 构建的限制.
It doesn't work for var
in a foreach
, but I suspect that's a limitation of the current Roslyn build.
推荐答案
您可以使用适用于 ToMinimalDisplayString()
的扩展方法,获取表示给定位置符号的最短合法字符串code>ISymbol(注意:它可以在`Roslyn.Compilers.CSharp.SymbolDisplay 中找到.
You can get the shortest legal string to represent a symbol at a given location using the ToMinimalDisplayString()
extension method that applies to ISymbol
(note: It's found in `Roslyn.Compilers.CSharp.SymbolDisplay.
免责声明:我在 Microsoft 的 Roslyn 团队工作.
Disclaimer: I work at Microsoft on the Roslyn team.
这篇关于从 ITypeSymbol 获取 TypeSyntax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!