【问题标题】:Using another method as a parameter使用另一种方法作为参数
【发布时间】:2012-11-06 23:06:20
【问题描述】:

有没有办法将一个方法用作另一个方法的参数。例如,对于给定函数 f 返回 2f(3) 的方法。我知道,我的代码不正确:我试图传达我想要的想法。

static double twofof3(double f(double x))
{
    return 2*f(3);
}

static double f(double x)
{
   return x * x;
}

twofof3 方法目前没有意义,因为它可以只用 f 方法来实现,但它更多是我感兴趣的概念。

【问题讨论】:

    标签: c# .net methods parameters


    【解决方案1】:

    是的,您可以使用Func 委托:

    static double twofof3(Func<double,double> f)
    {
        return 2*f(3);
    }
    
    static double function1(double x)
    {
       return x * x;
    }
    
    // ...
    
    Console.WriteLine(twofof3(function1));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-10
      • 2018-02-04
      相关资源
      最近更新 更多