Get Type of 'var' with Roslyn?

前端 未结 2 571
渐次进展
渐次进展 2021-02-02 13:04

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

namespace test
{
    public class TestClass
    {
        public void Hello()
        {
             


        
2条回答
  •  终归单人心
    2021-02-02 13:25

    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();
        foreach (var variableDeclaration in variableDeclarations)
        {
            var symbolInfo = semanticModel.GetSymbolInfo(variableDeclaration.Declaration.Type);
            var typeSymbol = symbolInfo.Symbol; // the type symbol for the variable..
        }
    }
    

提交回复
热议问题