C# 如何在委托函数中使用参数?
我希望能够在我使用委托创建的方法中放入任意数量的变量。我以为这是你通常的做法,但它似乎不起作用 我试着用这里的C# 如何在委托函数中使用参数?,c#,methods,lambda,parameters,delegates,C#,Methods,Lambda,Parameters,Delegates,我希望能够在我使用委托创建的方法中放入任意数量的变量。我以为这是你通常的做法,但它似乎不起作用 我试着用这里的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) {
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;
}
您需要将
h
定义为接受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)
MyFunction h = (x, rest) => ...;
参见
参数上的示例
允许调用者传入任意数量的参数。它不允许被调用方处理任意数量的参数
所以h
必须能够处理任何正数量的参数。需要这样写:
h(3,4,5)
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);
没有委托类型允许您指定要处理多少个参数。毕竟,调用者怎么知道要给你多少个参数呢?试试这个
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)}");
}
}