I am trying to write the following: I would like to write a method "A" which takes as parameter another method "B" as well as an unknown number of parameters for this method B. (params object[] args). Now, inside method A i would like to make a call to B with the parameters args. B will now return an object which I would like A to return as well.
This all sounds a bit strange, therefore I will add some example code:
public object A(Func<object> B, params object[] args)
{
object x = B.Method.Invoke(args);
return x;
}
The problem is, that Func does not work like that. Does anyone know a way of doing this?
Regards, Christian
void Main()
{
Func<int> m1=()=>1;
Console.WriteLine(A(m1));
Func<int,int> m2=i=>i;
Console.WriteLine(A(m2,55));
}
object A(Delegate B,params object[] args)
{
return B.Method.Invoke(B.Target,args);
}
...goodbye type-safety
Func<object>
is a delegate for a method that takes no arguments and returns object
. If you change it to Func<object,object>
, it will take an argument and return object:
public object A(Func<object, object> B, params object[] args)
{
object x = B(args);
return x;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With