Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

generics

I have these 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 the 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);
}

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>'

Can someone tell me how to resolve this? I see many other posts similar to this one but I'm not seeing the relationship.

like image 469
Claire Lee Avatar asked May 22 '13 07:05

Claire Lee


1 Answers

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>).

If you would have provided the line number of the compiler error, I suspect it would point to the methods OnEnter, etc.

like image 165
flq Avatar answered Nov 11 '22 00:11

flq