0

C# デリゲートに少し慣れてきました。「+=」演算子を使用して、複数のデリゲート インスタンスをデリゲートにサブスクライブできます。しかし、2番目のクラスのすべてのメソッドのデリゲートを持つコントローラークラスを持ち、メソッドを自動的に追加することも可能ですか?

簡略化されたコード (アクセス修飾子などを省略):

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 に答える