C# 何时使用SemanticModel.GetSymbolInfo以及何时使用SemanticModel.GetDeclaredSymbol
在某些情况下,当我尝试获取语法节点的ISymbol时,在使用SemanticModel.GetSymbolInfo时失败(获取null),但在使用SemanticModel.GetDeclaredSymbol时成功 我在下面附上了一个例子 所以我的问题是何时使用每种方法来获取语义模型C# 何时使用SemanticModel.GetSymbolInfo以及何时使用SemanticModel.GetDeclaredSymbol,c#,roslyn,roslyn-code-analysis,C#,Roslyn,Roslyn Code Analysis,在某些情况下,当我尝试获取语法节点的ISymbol时,在使用SemanticModel.GetSymbolInfo时失败(获取null),但在使用SemanticModel.GetDeclaredSymbol时成功 我在下面附上了一个例子 所以我的问题是何时使用每种方法来获取语义模型 public class Class1 { public System.String MyString { get; set; } public static void Main() {
public class Class1
{
public System.String MyString { get; set; }
public static void Main()
{
var str =
@"
namespace ClassLibrary31
{
public class Class1
{
public System.String MyString { get; set; }
}
}";
var syntaxTree = SyntaxFactory.ParseSyntaxTree(str);
MetadataReference[] metadataReferenceReferences = new MetadataReference[]
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
};
var compilation =
CSharpCompilation
.Create("TraceFluent",
new[] {syntaxTree},
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, warningLevel:1),
references: metadataReferenceReferences
);
var temp = compilation.Emit("temp");
var semanticModel = compilation.GetSemanticModel(syntaxTree, true);
PropertyDeclarationSyntax propertySyntaxNode =
syntaxTree.GetRoot()
.DescendantNodes()
.OfType<PropertyDeclarationSyntax>()
.First();
//var qu = propertySyntaxNode.q
//var symbolInfo = semanticModel.GetDeclaredSymbol(propertySyntaxNode);
var symbol = semanticModel.GetDeclaredSymbol(propertySyntaxNode) as IPropertySymbol;
var typeInfo = semanticModel.GetTypeInfo(propertySyntaxNode).Type;
}
}
公共类1
{
public System.String MyString{get;set;}
公共静态void Main()
{
var-str=
@"
命名空间类库31
{
公共班级1
{
public System.String MyString{get;set;}
}
}";
var syntaxTree=SyntaxFactory.ParseSyntaxTree(str);
MetadataReference[]metadataReferenceReferences=新MetadataReference[]
{
MetadataReference.CreateFromFile(typeof(object.Assembly.Location),
};
变量编译=
CSharp编译
.Create(“TraceFluent”,
新[]{syntaxTree},
选项:新的CSharpCompliationOptions(OutputKind.DynamicallyLinkedLibrary,警告级别:1),
引用:metadataReferenceReferences
);
var temp=compilation.Emit(“temp”);
var semanticModel=compilation.GetSemanticModel(syntaxTree,true);
PropertyDeclarationSyntax propertySyntaxNode=
syntaxTree.GetRoot()的
.DegeneratNodes()的
第()类
.First();
//var qu=propertySyntaxNode.q
//var symbolInfo=semanticModel.GetDeclaredSymbol(propertySyntaxNode);
var symbol=semanticModel.GetDeclaredSymbol(propertySyntaxNode)作为IPropertySymbol;
var typeInfo=semanticModel.GetTypeInfo(propertySyntaxNode).Type;
}
}
我相信您的意思是获取给定语法节点的符号,而不是获取树的语义模型
通常,当您想要获取声明的基础符号(类、属性、方法等)时,应该使用
GetDeclaredSymbol
。在内部,GetSymbolInfo
调用方法。你可以看到那里处理的不同案件。声明不会被处理,因此对于那些需要使用GetDeclaredSymbol
,您可以找到其内部结构。只是为了扩展:我发现的规则很有用:“如果一段语法的名称中包含DeclarationSyntax
,请使用GetDeclaredSymbol()
。否则,请使用GetSymbolInfo()
”。(这不是100%准确,但非常接近)