我刚刚熟悉了一下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