简体   繁体   中英

Receiving Generic Class as Parameter

I'm new at Generic Class. I'm making a game right now. I'll have many enemies, which all inherit from a generic EnemyBase class

public abstract class EnemyBase<TState, TTransition>
{
     protected StateMachine<TState, TTransition> m_FSM;
}

So as an example, I would have something like this:

public class EnemySquire : EnemyBase<EnemySquire.State, EnemySquire.StateTransition>
{
    public enum State
    {
        IDLE,
        WALK,
        ATTACKED,
        DEAD,
    }

    public enum StateTransition
    {
        FOUND_FREE_GRID,
        FINISHED,
        FREED,
        OUT_OF_LIFE,
        ATTACKED,
    }
}

So far so good. My problem is to receive EnemyBase class as parameter. I want to receive any kind of EnemyBase regardless of its generics. So:

public class Player
{
   public void Attack<TState, TTransition>()
   {
        EnemyBase<TState,TTransition> enemy = GetComponent<EnemyBase<TState,TTransition>>();
   }
}

This will work but Attack method is called inside another method so this other method must implement <TState, TTransition> as well and this other method is called by another one... and go on.

I would like to achieve something like:

public void Attack()
{
     EnemyBase enemy = GetComponent<EnemyBase>();
}

or

public void Attack()
{
     EnemyBase<,> enemy = GetComponent<EnemyBase<,>>();
}

I don't know if these sintaxes are correct or even if they exists but I just want to know if class is EnemyBase, regardless its generics.

Thanks

edit: added what generic type are used for

You can't have a field with an un-bound generic type like EnemyBase<,> .

You need to define either a non-generic base class for the generic one like EnemyBase<TState, TTransition> : EnemyBase or an interface like EnemyBase<TState, TTransition> : IEnemy .

Then you can have an EnemyBase or IEnemy field.

You need to do something like this:

public interface IEnemy
{
     StateMachine m_FSM { get ; }
}

public abstract class EnemyBase<TState, TTransition> : IEnemy
{

    protected StateMachine<TState, TTransition> m_FSM;
    StateMachine IEnemy.m_FSM => this.m_FSM;
}

public class StateMachine
{

}

public class StateMachine<TState, TTransition> : StateMachine
{

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM