gpt4 book ai didi

c# - 何时使用 SemanticModel.GetSymbolInfo 以及何时使用 SemanticModel.GetDeclaredSymbol

转载 作者:可可西里 更新时间:2023-11-01 08:10:54 25 4
gpt4 key购买 nike

在某些情况下,当我尝试获取语法节点的 ISymbol 时,使用 SemanticModel.GetSymbolInfo 会失败(获取 null),但使用 SemanticModel.GetDeclaredSymbol 会成功。

我在下面附上了一个例子。

所以我的问题是什么时候使用每种方法来获取语义模型?

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 symbolInfo = semanticModel.GetDeclaredSymbol(propertySyntaxNode);
var symbol = semanticModel.GetDeclaredSymbol(propertySyntaxNode) as IPropertySymbol;
var typeInfo = semanticModel.GetTypeInfo(propertySyntaxNode).Type;
}
}

最佳答案

我相信您的意思是获取给定语法节点的符号,而不是获取树的语义模型。

通常,当您想要获取声明的底层符号(类、属性、方法...)时,您应该使用GetDeclaredSymbol。在内部,GetSymbolInfo 调用 this方法。你可以看到那里处理的不同案例。不处理声明,因此对于那些您需要使用 GetDeclaredSymbol,您可以找到其内部结构 here .

关于c# - 何时使用 SemanticModel.GetSymbolInfo 以及何时使用 SemanticModel.GetDeclaredSymbol,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33492992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com