如何访问Func / Action委托参数值?

时间:2015-09-10 11:45:03

标签: c# delegates action func

我正在编写一种方法来对其他方法进行一些测量

像这样的东西,这个例子按预期运行:

public void RunMethodWithMeasurementsOn(Action actionToMeasure)
{
    //some stuff here

    actionToMeasure(); //call method execution

    //some stuff here
}

//method call would be:
RunMethodWithMeasurementsOn(new Action(actionToMeasure));

但我还需要为参数

的方法/程序做这项工作

例如

public void RunMethodWithMeasurementsOn(Action<int> actionToMeasure)
{
//stuff...

**how can I call actionToMeasure with it's parameters here?**

//stuff...
}

我想我可以像这样制作这种测量方法:

public void RunMethodWithMeasurementsOn(Action<int> actionToMeasure, int parameter)
{
//do stuff

actionToMeasure(parameter);

//do stuff
}

但这意味着,我的函数调用将是这样的 RunMethodWithMeasurementsOn(new Action<int>(actionToMeasure), parameterValue);

但我更愿意称之为这样 RunMethodWithMeasurementsOn(new Action<int>(actionToMeasure(parameterValue));

这可能吗?

1 个答案:

答案 0 :(得分:1)

是的,你可以这样做:

RunMethodWithMeasurementsOn(MethodWithNoParams);
RunMethodWithMeasurementsOn(() => { MethodWithOneParam(5); });

public void MethodWithNoParams()
{
    Console.WriteLine("MethodWithNoParams");
}

public void MethodWithOneParam(int a)
{
    Console.WriteLine("MethodWithOneParam: " + a);
}

并保持这种方式:

public void RunMethodWithMeasurementsOn(Action actionToMeasure)
{
    //some stuff here

    actionToMeasure(); //call method execution

    //some stuff here
}

技巧是:你传递一个匿名函数,没有参数,它本身调用参数化方法。