我怎么能把Func<;int,int,int>;C#中方法中的参数

本文关键字:int 参数 方法 Func lt 怎么能 gt | 更新日期: 2023-09-27 18:27:25

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

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));

我怎么能把Func<;int,int,int>;C#中方法中的参数

认为你想要这个:

public static void SomeTestMethod(int number,string str)
{
    Check( () => MethodOne(number,str));
}
public static int Check(Func<int> method)
{
         // some conditions 
      return method();
}
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);
}