Question

I'm translating an application from C++ to .NET/C#. However I'm struggling on how to express C++ functors in C#.

What would be the best way to translate the following expression to C#?

struct AircraftMover
{
    AircraftMover(float vx, float vy)
    : velocity(vx, vy)
    {
    }

    void operator() (Aircraft& aircraft, sf::Time) const
    {
        aircraft.accelerate(velocity);
    }

    sf::Vector2f velocity;
};
Was it helpful?

Solution

Replace the functor with a lambda in the C++ code, then use an equivalent lambda in the C# code.

Edit: Your C++ code from the comments modified to use lambdas:

void Player::initializeActions() {
  const float playerSpeed = 200.f;
  mActionBinding[MoveLeft].action =
      derivedAction<Aircraft>([=](Aircraft& a, Time) { a.accelerate(Vector2f(-playerSpeed, 0.f)); });
  ...
}

The equivalent C# code would look something like:

mActionBinding[MoveLeft].action = 
    new derivedAction<Aircraft>((Aircraft a, Time t) => a.accelerate(new Vector2f(-playerSpeed, 0.f)));

OTHER TIPS

You can create an Action like this:

Action<Aircraft, Time> airCraftMover = (a,t) => a.Accelerate(new Velocity(vx, vy));

This can then be passed around and applied to Aircraft at will.

To use it on an Aircraft, just call the Action like a method:

airCraftMover(aircraft, time);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top