Get Type of 'var' with Roslyn?

前端 未结 2 540
渐次进展
渐次进展 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<LocalDeclarationStatementSyntax>();
        foreach (var variableDeclaration in variableDeclarations)
        {
            var symbolInfo = semanticModel.GetSymbolInfo(variableDeclaration.Declaration.Type);
            var typeSymbol = symbolInfo.Symbol; // the type symbol for the variable..
        }
    }
    
    0 讨论(0)
  • 2021-02-02 13:35

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

    0 讨论(0)
提交回复
热议问题