先來個簡單的例子
RelayCommand(() => this.AddPerson(), () => this.CanAddPerson());
可以翻譯為 RelayCommand(參數一, 參數二);
參數一 :() => this.AddPerson()
參數二 :() => this.CanAddPerson()
() => this.AddPerson() 的意思是 一個沒有參數的方法,返回 this.AddPerson(),而這個返回值的類型不用指定,系統會自動判斷
同理 () => this.CanAddPerson() 就是 一個沒有參數的方法返回this.CanAddPerson()
例二:
internal abstract class GeoService
{
internal abstract void Update(GeoLocation location);
internal abstract string Name { get; }
}
private List<GeoService> _geoServices = new List<GeoService>();
private void NotifyLocationChanged(GeoLocation location)
{
_geoServices.ForEach(g => g.Update(location));
}
_geoServices是一個list,3.5給他擴展了一個foreach方法,這個方法可以遍歷一遍這個列表。
遍歷列表干什么呢?
可以對列表的每個項目做點事情,這時可以用個委托,這樣又要定義一個委托,語句太多了
=>就是lambda運算符,簡化這些語法。
定義一個匿名委托,左邊是參數,右邊是函數體。
參數g沒有定義類型是因為他自動推斷出類型來了,因為這個list能遍歷的東西只有這個。
這個語句里,就是遍歷這個list列表,對每個項執行一下update方法。
例三:
new Action<ImageEventArgs>((arg)=>xxx)
這是new了一個Action類型的委托,Action是沒有返回值的委托<ImageEventArgs>這個是委托的參數類型
(arg)是傳入的參數 =>后面是方法體
this.Dispatcher.BeginInvoke(
new Action<int, TestDetailClass, int>(
(idx, item,idd) =>m_TestForm[idx].Updatefun(item, idd)
), index, m_detail,id);
拆解:
最外層為BeginInvoke(方法的委托,傳參1,傳參2,傳參3)
這三個傳參提供給委托方法使用
方法的委托:new Action<委托參數類型>(執行的方法)
封裝一個方法,該方法定義了三個傳參的類型,並且它不返回值
執行的方法:(idx, item,idd) =>m_TestForm[idx].Updatefun(item, idd)
左邊是新聲明的傳入參數(對應的數據類型是int, TestDetailClass, int),他們的值來自於傳入的三個參數:index,m_detail,id
右邊m_TestForm[idx].Updatefun是一個有傳參的方法
其實就是把index,m_detail,id傳給m_TestForm[idx].Updatefun方法使用