Finding SyntaxNode of an ISymbol

时间:2016-01-17 18:54:49

标签: c# roslyn

Given a SemanticModel instance and an ISymbol assosiated with it, is it possible to get SyntaxNode of the ISymbol?

Basicly the opposite of GetDeclaredSymbol method of SemanticModel

the only way i am aware of is searching the SyntaxTree root with a predicate, is there a way to do it with less code?

1 个答案:

答案 0 :(得分:6)

要从SyntaxNode获取ISymbol声明,请使用ISymbol.DeclaringSyntaxReferences

请注意,它可以返回多个引用(例如,当您获得部分声明时)或者没有(当它在外部声明时)。

一个小例子:

var syntaxReference = propSymbol.DeclaringSyntaxReferences
                                .First()
                                .GetSyntax();

GetSyntax()将返回SyntaxNode,因此您仍应将其转换为您感兴趣的确切类型。