Groovy:'it' 与闭包的用法

Groovy: Usage of 'it' with closures

我想知道如何将隐式变量 'it' 传递给闭包。 见以下代码:

def myfunc(String name, Closure cl)
{
    println("name: ${name}")
    cl.call()
}

list = ['a', 'b']

list.each
{
    println("it1: ${it}")
}

list.each
{
    myfunc("f1")
    {
        println("it2: ${it}")
    }
}

list.each
{
    p ->
    myfunc("f2")
    {
        println("p: ${p}")
    }
}

结果输出为:

it1: a
it1: b
name: f1
it2: null
name: f1
it2: null
name: f2
p: a
name: f2
p: b

如何在第二个版本 (f1/it2) 中实现将隐式变量 it 传递给闭包?目前它是“空”。 我想在第二个版本中实现 'a'、'b' 在 'it' 之内。

问题的背景是,在 Jenkins Pipeline 中,以下代码

    mylist = ['a1', 'a2']
    mylist.each {
        dir ("xxxx") {
            echo "it in xxxx is ${it}"
        }
    }

it 打印出值 'a1' 和 'a2'。 这不符合 it 绑定到最外层闭包的理解。

对于 Jenkins,行为似乎有所不同。 我想实现完全相同的行为,我想知道如何做到这一点。

感谢所有反馈!

此致

马蒂亚斯

来自 jenkins 的

dir 不是一个函数 - 它是一个 jenkins 步骤,你的 groovy 函数示例不适用。

您必须检查它是否可以通过 groovy 定义的自定义步骤实现 https://rubix.nl/jenkins-creating-a-custom-pipeline-step-in-your-library/

或考虑创建自定义插件。

顺便说一句,这里是 dir jenkins 步骤的来源:https://github.com/jenkinsci/workflow-basic-steps-plugin/blob/master/src/main/java/org/jenkinsci/plugins/workflow/steps/PushdStep.java