var tree = CSharpSyntaxTree.ParseText(code); var mscorlib = MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location); var compilation = CSharpCompilation.Create("SymbolInfo", new[] { tree }, new[] { mscorlib }); var model = compilation.GetSemanticModel(tree);
var root = tree.GetRoot(); var variables = root.DescendantNodes().OfType<ExpressionStatementSyntax>() .Select(x => x.DescendantNodes().OfType<ArgumentSyntax>().First().Expression); var symbolInfos = variables.Select(x => model.GetSymbolInfo(x));
foreach (var infos in symbolInfos) { var symbol = infos.Symbol; string typeString = string.Empty; switch (symbol.Kind) { case SymbolKind.Field: var fieldSymbol = symbol as IFieldSymbol; typeString = fieldSymbol.Type.ToString(); break;
case SymbolKind.Local: var localSymbol = symbol as ILocalSymbol; typeString = localSymbol.Type.ToString(); break;
case SymbolKind.Method: var methodSymbol = symbol as IMethodSymbol; typeString = $"({string.Join(", ", methodSymbol.Parameters.Select(x => x.Type.ToString()))})" + $" -> {methodSymbol.ReturnType}"; break;
case SymbolKind.Property: var propertySymbol = symbol as IPropertySymbol; typeString = propertySymbol.Type.ToString(); break;