The type `T 'must be convertible in order to use it as a parameter of the` T' in a generic type or method

I have two main classes. First, the FSMSystem class:

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 second class, 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); } 

This results in the following error:

error CS0309: type ' T ' must be converted to ' FSMSystem<T> ' in order to use it as a parameter ' T ' in a generic type or method FSMSystem<T>

Can someone tell me how to solve this? I see many other posts similar to this, but I do not see the relationship.

+6
source share
2 answers

T FSMState must also be limited, otherwise it cannot be used as T of FSMSystem - which has restrictions on it ( T : FSMSystem<T> ).

If you specified the line number of the compiler error, I suspect that it will point to OnEnter methods, etc.

+8
source

This is a big help for me. Thank you all. I solved the problem. I misunderstood the syntax of "where".

Here is an updated 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); } 
0
source

Source: https://habr.com/ru/post/945545/


All Articles