相关疑难解决方法(0)

从ITypeSymbol获取TypeSyntax

我正在尝试使用Roslyn-CTP.

目前我正在尝试var用混凝土类型替换.

var i=1;
Run Code Online (Sandbox Code Playgroud)

应成为:

int i=1;
Run Code Online (Sandbox Code Playgroud)

找出推断类型很容易.但由于这部分发生在语义模型中,我得到了一个ITypeSymbol.替换发生在语法模型中,所以我需要一个TypeSyntax.由于我不想要一个膨胀的名称(global::System.Int32),转换依赖于上下文(using嵌套类型等).

作为Roslyn的一部分的Visual Studio版本已经在其"简化类型名称"quickfix中具有此功能,但查看示例我找不到一种简单的方法来执行此转换.


基于Kevin Pilch-Bisson的回答,我现在正在使用:

var location = document.GetSyntaxTree().GetLocation(node);
string name = variableType.ToMinimalDisplayString((Location)location, (SemanticModel)document.GetSemanticModel());
Run Code Online (Sandbox Code Playgroud)

ToMinimalDisplayString可以从a获得的位置CommonSyntaxTree.

另外一个复杂之处在于ToMinimalDisplayString,需要的类LocationSemanticModel,而document.GetSemanticModel()CommonSyntaxTree.GetLocation只返回一个接口.
我通过简单地转换到类来工作,这似乎现在有效.

嗯,看起来这些类是C#特定的,并且接口语言是独立的.


我已经在github上传了一个工作版本:https://github.com/CodesInChaos/Roslyn

它不适用于vara foreach,但我怀疑这是当前Roslyn构建的限制.

c# roslyn

11
推荐指数
1
解决办法
1501
查看次数

标签 统计

c# ×1

roslyn ×1