Is it possible to create a multicast delegate in C # 4.0 from any collection of method names?

I am writing a simple game in XNA and I ran into a problem with delegates. I use them to represent physics in a game, for example:

public delegate void PhysicsLaw(World world); //for gravitation static public void BallLawForGravity(World world) { if (world.ball.position.Y != world.zeroLevel) //v(t) = v0 + sqrt(c * (h - zeroLevel)) world.ball.speed.Y += (float)Math.Sqrt(0.019 * (world.zeroLevel - world.ball.position.Y)); } 

And I want to create multicast delegates for different objects / circumstances, consisting of many methods such as BallLawForGravity() , but I can only do this as follows:

 processingList = BallLawForBounce; processingList += BallLawForAirFriction; ... processingList += BallLawForGravity; 

Obviously, this does not look very good. Is there a standard way to create a multicast delegate from a collection of method names?

+4
source share
2 answers

For such tasks, use the static Delegate.Combine Method (Delegate[]) method.

  PhysicsLaw[] delegates = new PhysicsLaw[] { new PhysicsLaw( PhysicsLaw ), new PhysicsLaw( BallLawForAirFriction ) }; PhysicsLaw chained = (PhysicsLaw) Delegate.Combine( delegates ); chained(world); 

Additional examples .

Update You can use delegate creation through Reflection to do this, but I do not recommend it because it is a very slow technique.

+4
source

Say you announced

  public delegate void foo(int x); public static void foo1(int x) { } public static void foo2(int x) { } public static void foo3(int x) { } 

Now you can combine them directly with Delegate.Combine , if you don't mind typing the delegate name twice:

  foo multicast = (foo)Delegate.Combine(new foo[] { foo1, foo2, foo3 }); 

Or you can write a generic function to combine them if you don't mind typing the delegate name once:

  public static T Combine<T>(params T[] del) where T : class { return (T)(object)Delegate.Combine((Delegate[])(object[])del); } foo multicast2 = Combine<foo>(foo1, foo2, foo3); 

Or you can write a non-generic function to combine them, if you don't want to enter a delegate name at all:

  public static foo Combine(params foo[] del) { return (foo)Delegate.Combine(del); } foo multicast3 = Combine(foo1, foo2, foo3); 
+2
source

All Articles