0

我刚刚熟悉了一点 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());
4

2 回答 2

0

我认为这应该有效:

//编辑:不要简化MethodInfo mi1 = mi,否则你会得到一个叫做访问修改闭包的问题

    static IList<Action> getDelegatesFromObject(Object obj)
    {
        Type type = obj.GetType();

        List<Action> Actions = new List<Action>();
        foreach (MethodInfo mi in type.GetMethods())
        {
            MethodInfo mi1 = mi;

            Actions.Add(
                () => mi1.Invoke(obj, new object[] {})
            );
        }

        return Actions;
    }
于 2013-02-28T07:57:24.447 回答
0

现在我意识到这实际上只是在重新创建备受诟病的List<T>.ForEach. 为什么不直接使用它,因为它就在那里?


虽然它不能让你只调用.StartAllor .DriveAll,但你可以做一些简单的事情

class CallAller<T> : HashSet<T>
{
    public void CallAll(Action<T> action)
    {
        foreach (T t in this)
        {
            action(t);
        }
    }
}

var ca = new CallAller<Car>();
ca.Add(myFirstCar);
ca.Add(mySecondCar);

// Call a simple function
ca.CallAll(c => c.Start());

// Call a function taking parameters
ca.CallAll(c => c.SetRadio(88.1, RadioType.FM));

// Get return values... if you really need to.
Dictionary<Car, int> returnValues = new Dictionary<Car, int>();
ca.CallAll(c => returnValues.Add(c, c.GetNumberOfTyres()));

If you want something with actual methods to call and Intellisense, you'll need to look into code generation - it's possible, but I doubt it'd be worth the hassle.

于 2013-02-28T08:23:08.553 回答