- Home /
Question by
Sommy1491 · Jun 29, 2016 at 04:44 PM ·
unity5genericstypecasting
How to TypeCast T(Generic Type) into some Class DataType
Hi, I am little bit confuse in type casting through Generic Type. Here in my below code if my mainClassObject of Type T is a type of SignInEventHandler. I want to typecast T in SignInEventHandler type so i can access the SignInEvenHandler Members. Here SignInEventHandler is a Monobehaviour Class.
public override IEnumerator OnButtonClickEvent (Button buttonType, T mainClassObject){
//...............if mainClassObject type is SignInEventHandler...........//
if (mainClassObject.GetType () == typeof(SignInEventHandler)) {
// i want to do something like this//
SignInEventHandler signIn = (SignInEventHandler)mainClassObject.
}
yield return new WaitForSeconds (0.0f);
}
Comment
Answer by jdean300 · Jun 29, 2016 at 05:09 PM
This is because T is too unbounded for the compiler to promise any special behaviour. You can get away with this by using a safe cast:
SignInEventHandler signIn = mainClassObject as SignInEventHandler
if (signIn != null) //Will be null if the cast cannot be done
{
}
Answer by fafase · Jun 29, 2016 at 05:33 PM
You are misusing generic here. If you need your parameter to implement the type, then the parameter should be of that type. Actually, I would make SignInEventHandler an interface.