[英]How to get this working example example of delegates to pass lambda syntax as a parameter?
我正在嘗試在以下代碼中創建我自己可以理解的示例RelayCommand的方法:
return new RelayCommand(p => MessageBox.Show("It worked."));
構造函數是這樣的:
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
在我的最后一個問題中,喬恩·斯基特(Jon Skeet)向我指出了正確的方向,因此我可以得到一個示例(如下),該示例可以實現我想要的功能(傳遞一些方法名稱,如上面的MessageBox.Show所示)。 但是問題是,要使其正常工作,我必須取出所有的lambda語法(Action,Predicate等),這是我試圖理解的。
是否有辦法更改工作示例,使其執行相同的功能,但使用lambda語法作為參數,如下面的注釋行所示?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestLambda24
{
class Program
{
static void Main(string[] args)
{
int[] numbers = { 6, 3, 7, 4, 8 };
//Console.WriteLine("The addition result is {0}.", Tools.ProcessNumbers(p => Tools.AddNumbers, numbers));
Console.WriteLine("The addition result is {0}.", Tools.ProcessNumbers(Tools.AddNumbers, numbers));
//Console.WriteLine("The multiplication result is {0}.", Tools.ProcessNumbers(p => Tools.MultiplyNumbers, numbers));
Console.WriteLine("The multiplication result is {0}.", Tools.ProcessNumbers(Tools.MultiplyNumbers, numbers));
Console.ReadLine();
}
}
class Tools
{
public static int ProcessNumbers(Func<int[], int> theMethod, int[] integers)
{
return theMethod(integers);
}
public static int AddNumbers(int[] numbers)
{
int result = 0;
foreach (int i in numbers)
{
result += i;
}
return result;
}
public static int MultiplyNumbers(int[] numbers)
{
int result = 1;
foreach (int i in numbers)
{
result *= i;
}
return result;
}
}
}
好吧,你可以這樣做:
static void Main(string[] args)
{
int[] numbers = { 6, 3, 7, 4, 8 };
Console.WriteLine("The addition result is {0}.",
Tools.ProcessNumbers(p => Tools.AddNumbers(p), numbers));
Console.WriteLine("The multiplication result is {0}.",
Tools.ProcessNumbers(p => Tools.MultiplyNumbers(p), numbers));
Console.ReadLine();
}
換句話說,“給定一個數字數組,調用AddNumbers(或MultiplyNumbers)並傳入該數組,然后返回結果”。
但是,當您只能使用方法組時,這樣做就毫無意義。
喬恩說了什么(驚訝,驚喜!)
使用lambda的全部目的是動態創建函數,因此您不必靜態聲明它們。 例如,
Console.WriteLine("Mult value is {0}", Tools.ProcessNumbers(num => num.Aggregate(1, (i, j) => i*j), numbers));
Aggreagte()是一個擴展方法,(對於我使用的重載)采用種子值和函數。
首先將種子保存為累加器。 然后,對於系列中的每個元素,它將使用當前累加器和系列中的當前值調用給定函數,並將結果存儲在累加器中(以傳遞給下一個元素)。 最終返回的值將作為整體結果返回。
換句話說,它的作用與手動版本完全相同 ,不同之處在於它允許您傳遞“結果”的初始值以及在循環內調用的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.