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());