gpt4 book ai didi

c# - 如何使用 Roslyn 检测代码中的闭包?

转载 作者:太空狗 更新时间:2023-10-29 17:54:54 25 4
gpt4 key购买 nike

我能否检测到(使用 roslyn)lambda 主体中的 x 引用是对外部变量 x 的闭包,而不是 lambda 本身的某个局部变量?

var x = "foo";
var a = string[0];
a.Any(i => i == x);

最佳答案

是的。您可以使用 DataFlowAnalysis API。

var tree = CSharpSyntaxTree.ParseText(
@"
class C{
void M(){
var x = ""foo"";
var a = new string[0];
var testing = a.Any(i => i == x);
}
}
");
var Mscorlib = PortableExecutableReference.CreateFromAssembly(typeof(object).Assembly);
var compilation = CSharpCompilation.Create("MyCompilation",
syntaxTrees: new[] { tree }, references: new[] { Mscorlib });
var model = compilation.GetSemanticModel(tree);

var lambda = tree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Last();

var dataFlowAnalysis = model.AnalyzeDataFlow(lambda);
var capturedVariables = dataFlowAnalysis.Captured;

foreach(var variable in capturedVariables)
{
//Do something
}

关于c# - 如何使用 Roslyn 检测代码中的闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30300753/

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