Reputation: 306
Hey so I am trying to create a set of Generics and I cant seem to find the proper way to do this.
What I need is better showcased as an example implementation (which doesnt work):
public abstract class State<T,K> : StateMachine<StateType>{
public T Owner { get;set}
public Y Controller { get;set}
public void Setup(T Owner, Y Controller);
}
public abstract class StateMachine<StateType> where StateType : State<T,K>
where K : "MyOwnImplementationType typeof<this>??"// This refers to the "this" concrete type and not a special provided type, it since I cant seem to constraint to be the correct type, and inheritance type does not work
{
StateType[] states; // This needs to be the actual StateType and not the abstract class
public DoStuff(StateType t){
t.Setup(this, GetOwner()); // doesnt matter where Owner Comes from
}
}
public class ImplementationState : State<ImplementationStateMachine, ImplementationController> {
}
public class ImplementationStatemachine : StateMachine<ImplementationState, ImplementationController> {
}
If I replace MyOwnType with StateMachine, then it complains, and correctly, that my concrete implementation cant be mapped to the generic type.
I have been playing around with using interfaces and CoVariance/ ContraVariance but I cant seem to get the correct setup at all.
Is there anyway this is possible ? Or any workaround how to setup this? I am open to suggestions on another way to structure this sort of system.
The requirements is that I am able to access the correct types inside each class and not a generic variant.
Upvotes: 0
Views: 74
Reputation: 26372
The where
clauses, apply to the items in the Generic declaration. The only way to do what you are trying to do is this:
public abstract class StateMachine<StateType, T, K>
where StateType: State<T,K>
where K: MyOwnType
From the C# Language specification
A class declaration cannot supply type_parameter_constraints_clauses unless it also supplies a type_parameter_list.
There can be at most one where clause for each type parameter, and the where clauses can be listed in any order
Infering from the in any order and for for each type parameter, it's evident that you need to declare the T,K in the class declaration, to apply any constraints on them.
Upvotes: 1