1 string s = @"class C { void M() { } }"; 2 3 SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(text); 4 5 CSharpCompilation Compilation = CSharpCompilation 6 .Create("test") 7 .AddSyntaxTrees(tree) 8 .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)); 9 10 ///为了得到SemanticModel 11 SemanticModel semantic = Compilation.GetSemanticModel(tree); 12 13 //将树种的节点通过SemanticModelde得到Symbol 14 SyntaxNode syntaxNode; 15 tree.TryGetRoot(out syntaxNode); 16 //这个方法在下面的片段里 17 GetSymbolType(syntaxNode,semantic); 18 public static void GetSymbolType(SyntaxNode node,SemanticModel model) 19 { 20 foreach (var item in node.DescendantNodesAndSelf().OfType<MemberDeclarationSyntax>()) 21 { 22 //注意 GetDeclaredSymbol方法得到的传入的参数节点是 23 //MemberDeclarationSyntax的子类,可以查看它都有哪些重载 24 25 ISymbol type = model.GetDeclaredSymbol(item); 26 27 } 28 }