我刚刚熟悉了一点 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 的解决方案是我最喜欢的解决方案。它简单明了。作为一个小小的调整,我尝试了这个东西如何与动态类型的对象一起工作,它确实有效:控制器和受控对象之间的完全解耦。当然,这种“动态”的用法并不是每个人都喜欢……
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());