我是 Roslyn 的新手。我想知道是否有办法判断变量是否在语义模型中某个位置的范围内。为了介绍我正在做的事情的一些背景知识,我正在尝试转换 foreach
block ,这些 block 迭代 Select
的结果,例如形式的
foreach (string str in new int[0].Select(i => i.ToString()))
{
}
到
foreach (int item in new int[0])
{
string str = item.ToString();
}
这是我的代码修复提供程序的相关部分。目前,我正在将迭代变量硬编码为 item
:
var ident = SyntaxFactory.Identifier("item");
然后,我检索选择器的 SimpleLambdaExpressionSyntax
的 Body
,并且(在上述情况下)用 替换参数
获取 i
>itemitem.ToString()
:
var paramTokens = from token in selectorBody.DescendantTokens()
where token.Text == selectorParam.Identifier.Text
select token;
selectorBody = selectorBody.ReplaceTokens(paramTokens, (_, __) => ident);
我想知道是否有办法判断名为 item
的变量是否已经在 foreach
block 位置的范围内,所以我的代码修复提供者不会生成冲突的变量声明。这是否有可能以某种方式使用语义模型/符号/等来实现? API?
谢谢。
最佳答案
我想到了两种方法。
使用此测试代码,我可以测试不同的声明(字段、属性、变量、类名)
const string code = @"
public class AClass{
private int MyFld = 5;
protected double MyProp{get;set;}
public void AMethod(){
string myVar = null;
for (int myIterator=0; myIterator<10;myIterator++)
foreach (string str in new int[0].Select(i => i.ToString())){ }
}
public void AnotherMethod()
{
string anotherVar = null;
}
}";
-
void Main()
{
var tree = CSharpSyntaxTree.ParseText(code);
var root = tree.GetRoot();
var startNode = root
.DescendantNodes()
.OfType<SimpleLambdaExpressionSyntax>() // start at the Select() lambda
.FirstOrDefault();
FindSymbolDeclarationsInAncestors(startNode, "myVar").Dump(); // True
FindSymbolDeclarationsInAncestors(startNode, "anotherVar").Dump(); // False
CompilationLookUpSymbols(tree, startNode, "myVar").Dump(); // True
CompilationLookUpSymbols(tree, startNode, "anotherVar").Dump(); // False
}
// You could manually traverse the ancestor nodes, and find the different DeclarationSyntax-es.
// I may have missed some, like CatchDeclarationSyntax..
// Error-prone but more fun.
public bool FindSymbolDeclarationsInAncestors(CSharpSyntaxNode currentNode, string symbolToFind)
{
return currentNode
.Ancestors().SelectMany(a => a.ChildNodes()) // get direct siblings
.SelectMany(node => // find different declarations
(node as VariableDeclarationSyntax)?.Variables.Select(v => v.Identifier.ValueText)
?? (node as FieldDeclarationSyntax)?.Declaration?.Variables.Select(v => v.Identifier.ValueText)
?? (node as LocalDeclarationStatementSyntax)?.Declaration?.Variables.Select(v => v.Identifier.ValueText)
?? new[] {
(node as PropertyDeclarationSyntax)?.Identifier.ValueText,
(node as MethodDeclarationSyntax)?.Identifier.ValueText,
(node as ClassDeclarationSyntax)?.Identifier.ValueText,
})
.Any(member => string.Equals(member, symbolToFind));
}
// Or use the SemanticModel from the CSharpCompilation.
// Possibly slower? Also, not as much fun as manually traversing trees.
public bool CompilationLookUpSymbols(SyntaxTree tree, CSharpSyntaxNode currentNode, string symbolToFind)
{
var compilation = CSharpCompilation.Create("dummy", new[] { tree });
var model = compilation.GetSemanticModel(tree);
return model.LookupSymbols(currentNode.SpanStart, name: symbolToFind).Any();
}
关于c# - 如何判断变量是否在 Roslyn 的某个语法节点的范围内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42520733/