Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Specify that a function arg must inherit from one class, and implement an interface?

I'm making a game where each Actor is represented by a GameObjectController. Game Objects that can partake in combat implement ICombatant. How can I specify that arguments to a combat function must inherit from GameObjectController and implement ICombatant? Or does this indicate that my code is structured poorly?

public void ComputeAttackUpdate(ICombatant attacker, AttackType attackType, ICombatant victim)

In the above code, I want attacker and victim to inherit from GameObjectController and implement ICombatant. Is this syntactically possible?

like image 585
Nick Heiner Avatar asked Dec 02 '25 10:12

Nick Heiner


2 Answers

I'd say it probably indicates you could restructure somehow, like, have a base Combatant class that attacker and victim inherit from, which inherits from GameObjectController and implements ICombatant.

however, you could do something like

ComputeAttackUpdate<T,U>(T attacker, AttackType attackType, U victim)
      where T: ICombatant, GameObjectController
      where U: ICombatant, GameObjectController

Although I probably wouldn't.

like image 69
Jimmy Avatar answered Dec 04 '25 23:12

Jimmy


Presumably all ICombatants must also be GameObjectControllers? If so, you might want to make a new interface IGameObjectController and then declare:

interface IGameObjectController
{
    // Interface here.
}

interface ICombatant : IGameObjectController
{
    // Interface for combat stuff here.
}

class GameObjectController : IGameObjectController
{
    // Implementation here.
}

class FooActor : GameObjectController, ICombatant
{
    // Implementation for fighting here.   
}
like image 30
Mark Byers Avatar answered Dec 04 '25 23:12

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!