Roslyn:如何获得未解析的类型 [英] Roslyn : How to get unresolved types
问题描述
我使用的是 Roslyn 2012 年 9 月的 CTP.
I am using Roslyn's September 2012 CTP.
在 c# 代码文档中获取未解析类型的最优雅方法是什么?例如.类型 Guid 需要 System 命名空间.目前我有这样的事情:
What is the most elegant way to get unresolved types in a c# code document? Eg. Type Guid requires the System namespace. Currently I have something like this:
var semanticModel = (SemanticModel)document.GetSemanticModel();
var tree = (SyntaxTree)document.GetSyntaxTree();
//get unresolved types
var unresolvedTypes = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>()
.Where(x => semanticModel.GetSymbolInfo(x).Symbol == null);
使用 IdentifierNameSyntax 和 GetSymbolInfo 是否正确?
Is it correct to use IdentifierNameSyntax and GetSymbolInfo?
还有 GetSymbolInfo 和 GetTypeInfo 之间的区别是什么,它们看起来都与我非常相似.
Also what is the difference between GetSymbolInfo and GetTypeInfo, they both look very similar to me.
推荐答案
这里有几个问题.
问:使用IdentifierNameSyntax
是否正确?
答:您可能希望使用 SimpleNameSyntax
来处理解析泛型类型.此外,您可能不想查看所有 SimpleNameSyntax
元素.对于实际上不在类型上下文中的事物,您会得到误报(例如,想象一些像 var x = Console();
Q: Is it correct to use IdentifierNameSyntax
?
A: You probably want to use SimpleNameSyntax
to handle resolving generic types. Also, you may not want to look at ALL SimpleNameSyntax
elements. You will get false positives for things that are not actually in a type context (for example, imagine some code like var x = Console();
问:使用 GetSymbolInfo
并检查 null 是否正确?
A:是的,在这里检查是正确的.
Q: Is it correct to use GetSymbolInfo
and check for null?
A: Yes, this is the right thing to check here.
问:GetSymbolInfo
和 GetTypeInfo
有什么区别?
A:对于表示类型名称的语法,没有区别.但是,对于任意表达式,GetSymbolInfo
表示表达式的特定符号(例如,方法调用、索引器访问、数组访问、重载运算符等),GetTypeInfo
表示结果类型(以便在为表达式添加声明时知道要生成什么类型).以myString.GetHashCode()
"的InvocationExpressionSyntax
为例.GetSymbolInfo
将返回 GetHashCode()
的方法符号,而 GetTypeInfo
将返回 System.Int32
.
Q: What is the difference between GetSymbolInfo
and GetTypeInfo
?
A: For a syntax that represents a type name, there is no difference. However, for arbitrary expressions GetSymbolInfo
represents the specific symbol of the expression (for example, method call, indexer access, array access, overloaded operator, etc), and GetTypeInfo
represents the resulting type (so that you would know what type to generate if you were adding a declaration for the expression). Take for example the InvocationExpressionSyntax
for "myString.GetHashCode()
". GetSymbolInfo
would return the method symbol for GetHashCode()
, while GetTypeInfo
would return System.Int32
.
这篇关于Roslyn:如何获得未解析的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!