Reputation: 25924
I am trying to create a method which accepts different methods(Func
s) as a parameter.
I have a small problem in defining the Func
s arguments.
Suppose i need to call some thing like this :
public static void SomeTestMethod(int number,string str)
{
Check(MethodOne(number,str));
}
And For Check i have this:
public static int Check(Func<int,string,int> method)
{
// some conditions
method(where should i get the arguments ?);
}
Now my question is how should i set the needed arguments? I feel providing separate arguments for Check, is not elegant, since i need to call Check with the signature i provided in the TestMethod.
I dont want to have
Check(MethodOne,arg1,arg2,etc));
If it is possible i need to provide this signature instead:
Check(MethodOne(number,str));
Upvotes: 0
Views: 120
Reputation: 23324
I think you want this:
public static void SomeTestMethod(int number,string str)
{
Check( () => MethodOne(number,str));
}
public static int Check(Func<int> method)
{
// some conditions
return method();
}
Upvotes: 2
Reputation:
public static void Check<TReturnValue>(
Func<int, string, TReturnValue> method,
int arg1,
string arg2)
{
method(arg1, arg2);
}
calling:
public static SomeClass MethodOne(int p1, string p2)
{
// some body
}
Check(MethodOne, 20, "MyStr");
You have missed the type of return value (the last generic parameter means the type of return value). If you don't want to Func
return anything, just use Action
:
public static void Check(
Action<int, string> method,
int arg1,
string arg2)
{
method(arg1, arg2);
}
Upvotes: 1