Get TypeSyntax from ITypeSymbol

假如想象 提交于 2019-12-21 07:49:06

问题


I'm experimenting a bit with the Roslyn-CTP.

Currently I'm trying to replace var with the concrete type.

var i=1;

should become:

int i=1;

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.).

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.


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());

A location which ToMinimalDisplayString can be obtained from a CommonSyntaxTree.

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.

Hmm it looks like the classes are C# specific, and the interfaces language independent.


I've uploaded a working version on github: https://github.com/CodesInChaos/Roslyn

It doesn't work for var in a foreach, but I suspect that's a limitation of the current Roslyn build.


回答1:


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.

Disclaimer: I work at Microsoft on the Roslyn team.



来源:https://stackoverflow.com/questions/8231211/get-typesyntax-from-itypesymbol

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!