获取 var 的类型

要获取使用 var 声明的变量的实际类型,请在 SemanticModel 上调用 GetSymbolInfo()。你可以使用 MSBuildWorkspace 打开现有解决方案,然后枚举其项目及其文档。使用文档获取其 SyntaxRootSemanticModel,然后查找 VariableDeclarations 并检索声明变量的 Type 的符号,如下所示:

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