Get Type of 'var' with Roslyn?

旧巷老猫 提交于 2019-12-03 08:04:30

问题


I've got a .cs file named 'test.cs' which essentially looks like:

namespace test
{
    public class TestClass
    {
        public void Hello()
        {
            var x = 1;
        }
    }
}

I'm trying to parse this with Roslyn and get the type of x, which should be 'int', but I can only find out that it's type 'var', I can't seem to get the actual underlying type.

Here's basically what my code is now

var location = "test.cs";
var sourceTree = CSharpSyntaxTree.ParseFile(location);

var root = (CompilationUnitSyntax)sourceTree.GetRoot();
foreach (var member in root.Members)
{
    //...get to a method
    var method = (MethodDeclarationSyntax())member;
    foreach (var child in method.Body.ChildNodes())
    {
        if (child is LocalDeclarationStatementSyntax)
        {
            //var x = 1;
            child.Type.RealType()?
        }
    }
}

How can I get the real type of child? I've seen some things saying I should use a SemanticModel or Solution or a Workspace, but I can't seem to find out how load my test solution with Roslyn and then get the type of 'x'.

Also, I haven't been able to find any really good Roslyn documentation, it all seems to be spread out among a bunch of different versions and nothing for beginners like me. Does anyone know of an 'intro to Roslyn' or similar quickstart I could read up on?


回答1:


To get the actual type for a variable declared using var, call GetSymbolInfo() on the SemanticModel. You can open an existing solution using MSBuildWorkspace, then enumerate its projects and their documents. Use a document to obtain its SyntaxRoot and SemanticModel, then look for VariableDeclarations and retrieve the symbols for the Type of a declared variable like this:

var workspace = MSBuildWorkspace.Create();
var solution = workspace.OpenSolutionAsync("c:\\path\\to\\solution.sln").Result;

foreach (var document in solution.Projects.SelectMany(project => project.Documents))
{
    var rootNode = document.GetSyntaxRootAsync().Result;
    var semanticModel = document.GetSemanticModelAsync().Result;

    var variableDeclarations = rootNode
            .DescendantNodes()
            .OfType<LocalDeclarationStatementSyntax>();
    foreach (var variableDeclaration in variableDeclarations)
    {
        var symbolInfo = semanticModel.GetSymbolInfo(variableDeclaration.Declaration.Type);
        var typeSymbol = symbolInfo.Symbol; // the type symbol for the variable..
    }
}



回答2:


See the unit test called TestGetDeclaredSymbolFromLocalDeclarator in the Roslyn source tree.



来源:https://stackoverflow.com/questions/23878120/get-type-of-var-with-roslyn

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