簡體   English   中英

如何訪問Func / Action委托參數值?

[英]How to access Func/Action delegate parameter values?

我正在寫一種方法來對其他方法進行一些測量

像這樣,此示例按預期運行:

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));

這可能嗎?

是的,您可以這樣做:

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
}

訣竅是:您將沒有參數的匿名函數傳遞給它,該函數本身稱為參數化方法。

您必須像這樣通過它:

public void Foo(Action<int> action, int parameter)
{
    action(parameter);
}

第一個參數不包含動作的參數。 它是將要執行的唯一代碼。 因此,您必須以其他方式提供此參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM