[英]Lambda function using a delegate
我有以下几点:
class Program {
delegate int myDelegate(int x);
static void Main(string[] args) {
Program p = new Program();
Console.WriteLine(p.writeOutput(3, new myDelegate(x => x*x)));
Console.WriteLine("press [enter] to exit");
Console.ReadLine();
}
private string writeOutput(int x, myDelegate del) {
return string.Format("{0}^2 = {1}",x, del(x));
}
}
上面的方法writeOutput
是否必需? 可以在没有writeoutput
情况下writeoutput
以下内容以输出与上述相同的内容吗?
行Console.WriteLine("x^2 = {0}", new myDelegate(x => x*x));
修改以便将3馈入函数?
class Program {
delegate int myDelegate(int x);
static void Main(string[] args) {
Program p = new Program();
Console.WriteLine("x^2 = {0}", new myDelegate(x => x*x));
Console.WriteLine("press [enter] to exit");
Console.ReadLine();
}
}
显然不能这样写。 考虑一下:第二个代码中x的值是多少? 您创建委托的实例,但是何时调用它?
使用此代码:
myDelegate myDelegateInstance = new myDelegate(x => x * x);
Console.WriteLine("x^2 = {0}", myDelegateInstance(3));
您真的不需要脱盐。 但是为了工作,您需要更改此行:
Console.WriteLine("x^2 = {0}", new myDelegate(x => x*x));
有了这个:
Console.WriteLine("{0}^2 = {1}", x, x*x);
首先,您不需要代表。 您可以直接将其相乘。 但是首先,代表的更正。
myDelegate instance = x => x * x;
Console.WriteLine("x^2 = {0}", instance(3));
您应该像在第一个示例中一样将委托的每个实例都视为函数。 new myDelegate(/* blah blah */)
。 您可以直接使用lambda。
我假设您正在练习使用委托/ lambda,因为您可以编写以下代码:
Console.WriteLine("x^2 = {0}", 3 * 3);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.