1

I'm making a weapon/shooting system so that each Hero will be provided with it's own logic at compile time.

An example would look like:

class MageHero : Hero {

    MageHero(){
        base(new SingleShotAttackStrategy>());
    }
}

class BowmanHero : Hero {

    BowmanHero(){
        base(new MultishotAttackStrategy>());
    }
}

Each strategy has it's own logic for spawning bullets. Then, when I call Hero's Attack(), attached logic would be executed.

To the point

I come from Java. In Java, I can do that:

// there will be a different attack input for different shot types (single shot, multi shot...)
public class BaseAttackInput{}

class SingleShotInput extends BaseAttackInput{
    public int x, y;
    public int dirX, dirY;
    public int bulletSpeed;
}

public interface IAttackStrategy<T extends BaseAttackInput> {
    void attack(T input);
}

// specific strategy for a single shot
public class SingleShotStrategy implements IAttackStrategy<SingleShotInput>
{
    @Override
    public void attack(SingleShotInput input) {
        // spawn one bullet from the input's data
    }
}

public class MultiShotStrategy{...}

public class Hero{
    public IAttackStrategy strategy;

    void initialize(IAttackStrategy strategy){
        this.strategy = strategy;
    }
}

void testHero(){
    Hero hero = new Hero();
    hero.initialize(new SingleShotStrategy());
}

In the equivalent code in C#, I can't do that:

public class Hero{

    // ERROR, This needs to have specified generic types!
    public IAttackStrategy strategy;

    // this aswell...
    void initialize(IAttackStrategy strategy){
        this.strategy = strategy;
    }
}

And then comes the fun, because I have to add generic parameters to the Hero class, and then, provide generic parameters in each subclass of the Hero class etc...

What to do?

Jacob
  • 351
  • 2
  • 9
  • 1
    In C# you use the ":" instead of the words "extends" and "implements". As .NET only allows single inheritance, there is no ambiguity if you want to exted or implement. For generic constraints, you got the where clause. – Christopher Aug 29 '19 at 22:02
  • 1
    Just because you can, doesn't mean you should =]. [See this other question on Raw Types](https://stackoverflow.com/q/2770321/6383857) – StaticBeagle Aug 29 '19 at 22:05
  • As for overriding: Overriding has to be **allowed** by the base class. the keywords Virtual and Override do that. The only thing you can do without that allowance is hiding. But hiding is that one part of Polymorphy that nobody really uses. You only need ot know about it, so you do not accidentally hide. – Christopher Aug 29 '19 at 22:05
  • 3
    Raw types in Java are an unfortunate relic, not a benefit. – khelwood Aug 29 '19 at 22:06
  • @khelwood: "It is not a feature of the langauge - it is a bug of it." – Christopher Aug 29 '19 at 22:07

0 Answers0