我有一些需要重構的代碼有問題。現在它使用lambda作爲事件處理程序,但它們不能正確刪除。從我讀過的內容來看,這甚至不可能?無論如何,我想重寫它使用委託,而不是一個匿名函數,現在我的問題是,現在它需要一個行動作爲參數,我似乎無法弄清楚如何將行動傳遞給我的新代表。這是代碼:向事件處理程序參數添加一個動作c#
void RetrieveData(
int pointId,
int? chartCollectionId,
Action action)
{
if (pointId <= 0)
throw new ArgumentException("PointId not valid");
LastPointId = NextPointId;
NextPointId = pointId;
Clear();
_csr = new CustomerServiceRepository();
_csr.ServiceClient.GetChartDataCompleted += (se, ea) =>
{
_cachedCharts = ea.Result;
ChartDataRetrieved(ea.Result);
if (action != null)
action.Invoke();
_csr = null;
};
_csr.ServiceClient.GetChartDataAsync(
Settings.Current.Customer.CustomerName,
pointId,
chartCollectionId);
_csr.ServiceClient.GetChartDataCompleted -= (se, ea) => //remove after usage
{
_cachedCharts = ea.Result;
ChartDataRetrieved(ea.Result);
if (action != null)
action.Invoke();
_csr = null;
};
}
我在想,也許我可以創建以下文件:
public class extendedEventArgs : GetChartDataCompletedEventArgs
{
Action foo { get; set; }
}
void tang(object sender, extendedEventArgs e)
{
_cachedCharts = e.Result;
ChartDataRetrieved(e.Result);
if (action != null)
action.Invoke();
_csr = null;
}
而且通過行動在擴展事件參數的參數,但是當我嘗試使用像這樣
_csr.ServiceClient.GetChartDataCompleted += new EventHandler<extendedEventHandler>(tang);
它給出了一個錯誤:
Cannot implicitly convert type System.EventHandler<Conwx.Net.Client.CustomerClient.Controls.ChartControls.ChartListForecast.extendedEventArgs>' to System.EventHandler<Conwx.Net.Client.Framework.CustomerServiceReference.GetChartDataCompletedEventArgs>'
我在這裏做錯了什麼?替代解決方案也受到歡迎。
.K
這看起來很有希望,非常感謝! – Keller