开发者

Can a multicast delegate in C# 4.0 be created from some sort of collection of method names?

开发者 https://www.devze.com 2023-03-13 07:31 出处:网络
I\'m writing a simple game in XNA and I\'ve 开发者_高级运维faced a problem with delegates. I use them to represent physics in the game, e.g.:

I'm writing a simple game in XNA and I've 开发者_高级运维faced a problem with delegates. I use them to represent physics in the game, e.g.:

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 from many methods such as BallLawForGravity(), but I can do it only like this:

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

Obviously, it doesn't look good. Is there any standard way to create a multicast delegate from collection of method names?


Use the static method Delegate.Combine Method (Delegate[]) for such tasks.

 PhysicsLaw[] delegates = new PhysicsLaw[] {
        new PhysicsLaw( PhysicsLaw ),
        new PhysicsLaw( BallLawForAirFriction )
    };

    PhysicsLaw chained = (PhysicsLaw) Delegate.Combine( delegates );
    chained(world);

More examples.

Update You can use the creating delegate via Reflection for this but I don't recommend it, because it's very slow technic.


Let's say you've declared

    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 type the delegate name at all:

    public static foo Combine(params foo[] del)
    {
        return (foo)Delegate.Combine(del);
    }

    foo multicast3 = Combine(foo1, foo2, foo3);
0

精彩评论

暂无评论...
验证码 换一张
取 消