Mohammed Hossain
Mohammed Hossain

Reputation: 1319

Complex use of delegates

C# newbie here.

In one of my classes (an Entity class, to be precise), I have a delegate that takes in an Entity and another related class:

public delegate void FiringFunc(Entity e, BulletFactory fact)

and a loop in the Entity class that calls this function every frame (if its defined):

FiringFunc firingFunc = null; //defined later
if(firingFunc)
    firingFunc(this, someBulletFactory);    

As one could probably tell, this is a delegate that serves as a bullet firing function (you would code something like a timer for the bullet, the angles to fire at, etc). However, a thought occurred to me: what if I wanted the bullet to have a slight difference, but still remain the same (something like a tad bit slower, a slightly different color, in a different direction, etc). I would have to create another function to serve as the delegate - this seemed wrong to me.

Here is an example of what creating and setting the delegate would look like:

Entity e = new Entity( ... )
e.firingFunc = FiringFunctions.SomeFiringFunctionName;

Is there a way I could add parameters to this? It would be great if I could do something akin to the following:

e.firingFunc = FiringFunctions.SomeFiringFunctionName(someChange1, someChange2);

Upvotes: 2

Views: 152

Answers (2)

Chris Shain
Chris Shain

Reputation: 51319

Try

e.firingFunc = 
    (Entity e, BulletFactory fact) => 
        FiringFunctions.SomeFiringFunctionName(e, fact, "foo", 5);

This creates a new anonymous function (the lambda) that calls FiringFunctions.SomeFiringFunctionName with the included parameters.

This assumes that FiringFunctions.SomeFiringFunctionName is defined as:

public void SomeFiringFunctionName(Entity e, BulletFactory fact, String someString, Int32 someInt) { 
  //...  do whatever here
}

Upvotes: 3

mellamokb
mellamokb

Reputation: 56769

You could also use a custom interface and take advantage of polymorphism (ya, it needs a better name).

public interface IFiringActionProvider
{
    public void Fire(Entity e, BulletFactory fact);
}

Then in your same Entity class:

IFiringActionProvider firingFunc = null; //defined later
if (firingFunc != null)
    firingFunc.Fire(this, someBulletFactory);

You can create custom instances in whatever form you'd like, such as:

public class CustomColorFiringActionProvider : IFiringActionProvider
{
    private Color color;
    public CustomColorFiringActionProvider(Color c) { this.color = c; }
    public void Fire(Entity e, BulletFactory fact)
    {
        // do something, using color
    }
}

Just to add another similar approach (not necessarily better).

Upvotes: 1

Related Questions