0

我正在尝试创建一个接受不同方法Func作为参数的方法。
我在定义Funcs 参数时遇到了一个小问题。假设我需要调用这样的东西:

public static void SomeTestMethod(int number,string str)
{
    Check(MethodOne(number,str));
}

为了检查我有这个:

public static int Check(Func<int,string,int> method)
{
         // some conditions 
      method(where should i get the arguments ?);
}

现在我的问题是我应该如何设置所需的参数?我觉得为 Check 提供单独的参数并不优雅,因为我需要使用我在 TestMethod 中提供的签名来调用 Check。
我不想拥有

Check(MethodOne,arg1,arg2,etc));  

如果可能,我需要提供此签名:

Check(MethodOne(number,str));
4

2 回答 2

2

你想要这个:

public static void SomeTestMethod(int number,string str)
{
    Check( () => MethodOne(number,str));
}

public static int Check(Func<int> method)
{
         // some conditions 
      return method();
}
于 2014-10-21T06:53:51.210 回答
1
public static void Check<TReturnValue>(
                       Func<int, string, TReturnValue> method, 
                       int arg1, 
                       string arg2)
{
    method(arg1, arg2);
}

调用:

public static SomeClass MethodOne(int p1, string p2)
{
   // some body
}

Check(MethodOne, 20, "MyStr");

您错过了返回值的类型(最后一个泛型参数表示返回值的类型)。如果您不想Func返回任何东西,只需使用Action

public static void Check(
                       Action<int, string> method, 
                       int arg1, 
                       string arg2)
{
    method(arg1, arg2);
}
于 2014-10-21T06:38:27.907 回答