我無法防止重複的代碼。委託傳遞爲通用參數時調用C#委託方法
目前,我有以下方法:
protected delegate bool CallbackDelegate<T>(T param, out string result);
protected delegate bool CallbackDelegate<T, U>(T param1, U param2, out string result);
protected bool ClientCtrlCallback<T>(T param, CallbackDelegate<T> callbackMethod)
{...}
protected bool ClientCtrlCallback<T,U>(T param1, U param2, CallbackDelegate<T,U> callbackMethod)
{...}
兩個ClientCtrlCallback方法具有相同的代碼(檢查溝通渠道的有效性,try-catch塊,獲取鎖等),在調用CallbackDelegate方法周圍建。
我一直在試圖合併這些ClientCtrl方法,但沒有成功,因爲委託約束是不被允許的。這是據我得到:(爲清楚起見移除不必要的代碼)
protected delegate bool CallbackDelegate1<T>(T param, out string result);
protected delegate bool CallbackDelegate2<T, U>(T param1, U param2, out string result);
protected const string METHOD_MY_DELEGATE1 = "CallbackDelegate1";
protected const string METHOD_MY_DELEGATE2 = "CallbackDelegate2";
protected interface ParameterSet { };
protected class OneParameter<T>: ParameterSet { public T p1; };
protected class TwoParameters<T,U> : ParameterSet { public T p1; public U p2; };
protected bool ClientCtrlCallback<D,T,U>(ParameterSet parameterset, D callbackMethod, string successLog = null) // where MyDelegate : delegate //not allowed
{
// delegate constrained is not allowed, so check it here
if (!typeof(D).IsSubclassOf(typeof(Delegate)))
return false;
// check name of method (this works)
string methodName = (callbackMethod as Delegate).Method.Name;
// Call the delegate // doesn't work.
string result;
switch (methodName)
{
case METHOD_MY_DELEGATE1:
// doesnt work
//(callbackMethod as Delegate)((parameterset as OneParameter<T>).p1, out result);
break;
case METHOD_MY_DELEGATE2:
// doesnt work
//(callbackMethod as Delegate)((parameterset as TwoParameters<T, U>).p1, (parameterset as TwoParameters<T, U>).p2, out result); // doesnt work
break;
}
return true;
}
它開始變得醜陋了參數類。交換機比較代表的姓名會變得更糟(我也不喜歡每個人都給他們一個不同的名字)。然後,當我想調用Delegate的方法時,總是有麻煩:編譯時錯誤Method name expected
我不明白爲什麼我可以從Delegate獲取方法名稱,但不調用Delegate的方法。我錯過了什麼大事?
也許用類,接口,虛擬方法和所有爵士樂來代替整個事物? –
不要這樣做。如果在這兩種方法中存在多餘的重複代碼,則將重複的代碼抽象爲輔助方法。但不要更改兩個方法的簽名,然後嘗試在運行時強制實現類型系統。更一般地說:人們花費太多時間擔心小的重複。正如你所發現的那樣,它們的重複數據刪除非常昂貴,而且這種努力可能會更好地用於編寫測試,尋找錯誤,設計下一個版本等等。 –
嘗試使用Action <>? – lindexi