我剛剛熟悉了一下C#代表。可以通過「+ =」操作符將多個委託實例訂閱到委託。但是,是否也有可能擁有一個控制器類,它擁有第二個類中所有方法的委託,並自動添加方法,即不必爲每個方法單獨添加(甚至不知道)每個方法給相應的委託?訂閱代理類的所有方法
在簡化代碼(省略訪問修飾符等):
class Car
{
void Start();
void Drive();
}
// I would like to have the following class generated automatically
// without needing to repeat all the methods of Car, i.e.
// without declaring a delegate instance for each of them
class CarController
{
delegate void DoSomething();
DoSomething StartAll;
DoSomething DriveAll;
void Subscribe(Car anotherCar)
{
StartAll += anotherCar.Start;
DriveAll += anotherCar.Drive;
}
}
編輯: Rawling的解決方案是,我最喜歡的一個。它很簡單明瞭。作爲一個小小的調整,我已經嘗試過如何使用動態類型的對象,它確實有效:完成Controller和受控對象之間的解耦。的「動態」當然,這樣的用法是不是每個人的口味......
public class CallAller2 : HashSet<dynamic>
{
public void CallAll(Action<dynamic> action)
{
foreach (dynamic t in this)
{
try {action(t);} catch (RuntimeBinderException) {};
}
}
}
class Bike
{
void Drive();
}
CallAller2 ca = new CallAller2();
ca.Add(new Car());
ca.Add(new Bike());
ca.CallAll(c => c.Start()); // is ignored by Bike which does not implement it
ca.CallAll(c => c.Drive());
這聽起來像你正在描述你的想法*解決方案*的一個問題 - 你* *沒有告訴我們的問題。如果你能清楚地說明*問題而不是「解決方案」,那麼我們更有可能產生好的答案。 – 2013-02-28 07:50:22
我想是的。只要簽名與委託相匹配,一切都應該起作用。你試過了嗎? – 2013-02-28 07:51:47
@Damien_The_Unbeliever:我遇到的問題是我有一個數據模型(樹)必須與兩個不同的視圖(一個標準的TreeView和我的自定義SceneGraph)同步。當其中一個視圖發生變化時,數據必須更新,並且直接在代碼中操作數據時,視圖應該被更新。甚至在未來,我可能想要一個依賴於相同接口的撤銷管理器或腳本引擎。當我想像上面顯示的那樣做時,可能我想的太複雜了,但我想盡可能地分離所有不同的數據結構。 – oliver 2013-02-28 07:58:07