作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
在某些情况下,当我尝试获取语法节点的 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/
在某些情况下,当我尝试获取语法节点的 ISymbol 时,使用 SemanticModel.GetSymbolInfo 会失败(获取 null),但使用 SemanticModel.GetDeclar
我是一名优秀的程序员,十分优秀!