[英]How to change delegate expression to lambda?
我正在閱讀一些代碼,看到了以下內容:
Method.Find(delegate(Department depts) {
return depts.Id == _departmentId; });
T Find
方法具有以下描述:
public T Find(Predicate<T> match);
// Summary:
// Searches for an element that matches the conditions defined by the specified
// predicate, and returns the first occurrence within the entire
// System.Collections.Generic.List<T>.
//
// Parameters:
// match:
// The System.Predicate<T> delegate that defines the conditions of the element
// to search for.
// (...)
是否可以重寫此方法以將lambda表達式作為參數,如果可以,怎么做?
如果您要傳遞一個lambda表達式作為參數,該方法已經可以接受。
該方法只是表明它接受委托。 有幾種定義委托的方法:
Find(a => true)
) Find(someNamedMethod)
Find((Predicate<Whatever>)Delegate.CreateDelegate(typeof(SomeClass), someMethodInfo))
) 無需重新編寫方法,就可以使用lambda了,如下所示:
Method.Find(x => x.Id == _departmentId );
您提供的代碼是一個匿名委托
Method.Find(delegate(Department depts) {
return depts.Id == _departmentId; });
lambda是一個匿名函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.