I have a function:
private void SetupCallbacks()
{
Type actionType = Type.GetType(CardData.ActionFile);
if (actionType == null)
return;
// To get any particular method from actionType, I have to do the following
MethodInfo turnStarted = actionType.GetMethod(CardData.TurnStartedMethod);
if (turnStarted != null)
{
Delegate d = Delegate.CreateDelegate(typeof(Action<bool>), turnStarted);
Action<bool> turnStartedAction = (Action<bool>)d;
TurnManager.Instance.OnTurnStarted += turnStartedAction;
}
...
}
actionType
is a class that contains several static methods. These methods are stored as strings in the CardData object. I provided an example using the OnTurnStarted
callback. It is very clunky to write out all that code repeatedly each time I want to add another callback. I've tried creating a function:
private void SetupCallback<TDelegate>(Type actionType, string method, TDelegate delagateToAddThisTo) where TDelegate : Delegate
{
MethodInfo methodInfo = actionsContainerClass.GetMethod(method);
if (methodInfo != null)
{
Delegate d = Delegate.CreateDelegate(typeof(Action<Card>), methodInfo);
TDelegate t = (TDelegate)d;
delagateToAddThisTo += t;
}
}
However, where TDelegate : Delegate
doesn't work. I can't just do some type checking in the method (ie:
if(typeof(TDelegate).IsSubclassOf(typeof(Delegate)) == false)
{
throw new InvalidOperationException("Card::SetupCallback - " + typeof(TDelegate).Name + " is not a delegate");
}
because delagateToAddThisTo
which is of type TDelegate and needs to be able to be added to.
Thank you in advance.