var tree = CSharpSyntaxTree.ParseText(code); var mscorlib = MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location); var compilation = CSharpCompilation.Create("TypeInfo", new[] { tree }, new[] { mscorlib }); var model = compilation.GetSemanticModel(tree);
var root = tree.GetRoot(); var values = root.DescendantNodes().OfType<ArrayCreationExpressionSyntax>().First() .ChildNodes().OfType<InitializerExpressionSyntax>().First() .ChildNodes(); foreach (var item in values) { var info = model.GetTypeInfo(item); Console.WriteLine($"{item.WithoutTrivia().ToFullString()} : {info.Type}, " + $"(minimum){info.Type?.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)}, " + $"(converted){ info.ConvertedType}"); } Console.WriteLine();
var calling = root.DescendantNodes().OfType<InvocationExpressionSyntax>().First(); var symbols = calling.ArgumentList.Arguments.Select(a => a.Expression); Console.WriteLine("first " + calling.WithoutTrivia().ToString()); foreach (var item in symbols.Select((v, i) => new { Index = i, Value = v })) { var info = model.GetTypeInfo(item.Value); Console.WriteLine($"No.{item.Index} : {info.Type}, " + $"(minimum){info.Type?.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)}, " + $"(converted){info.ConvertedType}"); } Console.WriteLine();
calling = root.DescendantNodes().OfType<InvocationExpressionSyntax>().Skip(1).First(); symbols = calling.ArgumentList.Arguments.Select(a => a.Expression); Console.WriteLine("second " + calling.WithoutTrivia().ToString()); foreach (var item in symbols.Select((v, i) => new { Index = i, Value = v })) { var info = model.GetTypeInfo(item.Value); Console.WriteLine($"No.{item.Index} : {info.Type}, " + $"(minimum){info.Type?.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)}, " + $"(converted){info.ConvertedType}"); }