[英]Receiving Generic Class as Parameter
I'm new at Generic Class.我是 Generic Class 的新手。 I'm making a game right now.我现在正在做一个游戏。 I'll have many enemies, which all inherit from a generic EnemyBase class我会有很多敌人,它们都继承自一个通用的 EnemyBase 类
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.我的问题是接收EnemyBase
类作为参数。 I want to receive any kind of EnemyBase regardless of its generics.我想接收任何类型的 EnemyBase,而不管它的泛型如何。 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.这会起作用,但是 Attack 方法在另一个方法中被调用,所以这个另一个方法也必须实现<TState, TTransition>
并且这个另一个方法被另一个方法调用......然后继续。
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.我不知道这些语法是否正确,或者它们是否存在,但我只想知道类是否是 EnemyBase,而不管它的泛型。
Thanks谢谢
edit: added what generic type are used for编辑:添加了通用类型用于
You can't have a field with an un-bound generic type like EnemyBase<,>
.你不能有一个像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
.您需要为通用类定义一个非通用基类,如EnemyBase<TState, TTransition> : EnemyBase
或接口如EnemyBase<TState, TTransition> : IEnemy
。
Then you can have an EnemyBase
or IEnemy
field.然后你可以有一个EnemyBase
或IEnemy
字段。
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
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.