Consider the following pseudo code:
TResult Foo(Func f, params object[] args)
{
TResult result = f(args);
You can use Delegate
with DynamicInvoke
.
With that, you don't need to handle with object[]
in f
.
TResult Foo(Delegate f, params object[] args)
{
var result = f.DynamicInvoke(args);
return (TResult)Convert.ChangeType(result, typeof(TResult));
}
Usage:
Func f = (name, age, active) =>
{
if (name == "Jon" && age == 40 && active)
{
return true;
}
return false;
};
Foo(f,"Jon", 40, true);
I created a fiddle showing some examples: https://dotnetfiddle.net/LdmOqo
Note:
If you want to use a method group
, you need to use an explict casting to Func
:
public static bool Method(string name, int age)
{
...
}
var method = (Func)Method;
Foo(method, "Jon", 40);
Fiddle: https://dotnetfiddle.net/3ZPLsY