【问题标题】:How can I use params in a delegate function?如何在委托函数中使用参数?
【发布时间】:2021-07-01 04:02:01
【问题描述】:

我希望能够在我使用委托创建的方法中放入任意数量的变量。我认为这通常是你的做法,但它似乎不起作用。

我正在尝试在这里使用h(x,y,z) 来实现

delegate double MyFunction1(double x);
delegate double MyFunction2(double x, double y);
delegate double MyFunction(double x, params double[] args);

static void Main(string[] args)
{
    MyFunction1 f = x => x;
    MyFunction2 g = (x,y) => x * y;

    MyFunction h = (x, y, z) => x * y * z;
}

【问题讨论】:

    标签: c# methods lambda parameters delegates


    【解决方案1】:

    您需要将h 定义为接受A double[] 的方法。 params 作为单独的参数调用,但作为一个数组传递给方法:

    delegate double MyFunction(params double[] args);
    
    static void Main(string[] args)
    {
        MyFunction h = args => { 
            var result = 1.0; 
            foreach (var value in args) { result *= value; }; 
            return result; 
        };
    }
    

    那么你可以这样称呼它:

    h(3,4,5)
    

    查看here上的示例

    【讨论】:

      【解决方案2】:

      试试这个。

      delegate double MyFunction(double x, params double[] args);
      class Program
      {
          static public double Hoo(double x, params double[] args)
          {
              foreach (var item in args)
              {
                  x *= item;
              }
              return x;
          }
          static void Main(string[] args)
          {
              MyFunction h = Hoo;
              Console.WriteLine($"h (with 1 params) : {h.Invoke(5)}");
              Console.WriteLine($"h (with 2 params) : {h.Invoke(5, 5)}");
              Console.WriteLine($"h (with 3 params) : {h.Invoke(5, 5, 5)}");
              Console.WriteLine($"h (with 4 params) : {h.Invoke(5, 5, 5, 5)}");
          }
      }
      

      【讨论】:

        【解决方案3】:

        params 允许 调用者 传入任意数量的参数。它不允许 被调用者 处理他们想要的任意数量的参数。

        所以h 必须能够处理任何正数的参数。需要这样写:

        MyFunction h = (x, rest) => ...;
        

        x 是 double,rest 是 double[],可以包含 0 个或多个元素。

        如果你想计算所有参数的乘积:

        MyFunction h = (x, rest) => x * rest.Aggregate(1.0, (y, z) => y * z);
        

        如果您只想处理 3 个参数,请改用这样的委托:

        delegate double MyFunction3(double x, double y, double z);
        

        没有委托类型允许您指定要处理的参数数量。毕竟,调用者怎么知道要给你多少参数呢?

        【讨论】:

          猜你喜欢
          • 2022-11-19
          • 2017-04-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多