'C# delegate with pre-set parameters [duplicate]
I need to do something similar with command pattern, but in terms of delegate or something similar.
It should look like this:
private MyFunc Method1() {
MyFunc func;
/*
set all parameters to func
*/
return func;
}
private void Method2()
{
var funcWithAllParameters = Method1();
funcWithAllParameters.Invoke();
}
private MyFunc(a lot of parameters) {}
Solution 1:[1]
You can do this using a lambda function, which supplies the parameters for and calls MyFunc. The result is an Action delegate, which has the signature void ()
private Action Method1() {
return () => MyFunc(new Type1(), null);
}
private void Method2()
{
var funcWithAllParameters = Method1();
funcWithAllParameters.Invoke();
}
private void MyFunc(Type1 p1, Type2 p2)
{
//
}
Solution 2:[2]
You can put the values into a closure like so:
private Func<TResult> Method1()
=> () => MyFunc(/*a lot of parameters*/"param1", 12, ...);
Thus you could load the parameters in the closure and use the Function afterwards:
var func = Method1();
var result = func();
And of course you can also use the function as parameter for other functions:
private TResult SomeOtherMethod(Func<TResult> functionWithSetParameters)
=> functionWithSetParameters();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Clemens |
