[英]The type 'T' must be convertible in order to use it as parameter 'T' in the generic type or method
I have these two main classes.我有这两个主要课程。 First the FSMSystem class:
首先是 FSMSystem 类:
public class FSMSystem<T> : MonoBehaviour where T : FSMSystem<T>
{
private T m_Owner = default(T);
protected FSMState<T> currentState;
private Dictionary<int, FSMState<T>> m_states;
public FSMSystem(T owner)
{
m_Owner = GameObject.FindObjectOfType(typeof(T)) as T; //owner;
m_states = new Dictionary<int, FSMState<T>>();
}
protected void AddState( FSMState<T> state )
{
m_states.Add( state.GetStateID(), state );
}
}
And the second class, FSMState:第二个类,FSMState:
public abstract class FSMState<T>
{
public abstract int GetStateID();
public abstract void OnEnter (FSMSystem<T> fsm, FSMState<T> prevState);
public abstract void OnUpdate (FSMSystem<T> fsm);
public abstract void OnExit (FSMSystem<T> fsm, FSMState<T> nextState);
}
It leads to the following error:它导致以下错误:
error CS0309: The type '
T
' must be convertible to 'FSMSystem<T>
' in order to use it as parameter 'T
' in the generic type or method 'FSMSystem<T>
'错误 CS0309:类型“
T
”必须可转换为“FSMSystem<T>
”,以便将其用作泛型类型或方法“FSMSystem<T>
”中的参数“T
”
Can someone tell me how to resolve this?有人可以告诉我如何解决这个问题吗? I see many other posts similar to this one but I'm not seeing the relationship.
我看到许多其他帖子与此类似,但我没有看到这种关系。
The T
of FSMState
must also be constrained, otherwise it cannot be used as the T
of FSMSystem
- which has constraints placed on it ( T : FSMSystem<T>
).所述
T
的FSMState
也必须限制,否则就不能用作T
的FSMSystem
-其具有置于其上的约束( T : FSMSystem<T>
If you would have provided the line number of the compiler error, I suspect it would point to the methods OnEnter
, etc.如果您提供了编译器错误的行号,我怀疑它会指向
OnEnter
等方法。
It's big help to me.对我帮助很大。 thank you all.
谢谢你们。 I resolved the problem.
我解决了这个问题。 I misunderstood about 'where' syntax.
我误解了“where”语法。
Here is the revised version that works.这是有效的修订版本。
public class FSMSystem<T> : MonoBehaviour where T : FSMSystem<T>
{
private T m_Owner = default(T);
protected FSMState<T> currentState;
private Dictionary<int, FSMState<T>> m_states;
public FSMSystem()
{
m_Owner = this as T;
m_states = new Dictionary<int, FSMState<T>>();
}
protected void AddState( FSMState<T> state )
{
m_states.Add( state.GetStateID(), state );
}
}
public abstract class FSMState<T> where T : FSMSystem<T>
{
public abstract int GetStateID();
public abstract void OnEnter (T fsm, FSMState<T> prevState);
public abstract void OnUpdate (T fsm);
public abstract void OnExit (T fsm, FSMState<T> nextState);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.