【发布时间】:2017-07-05 17:09:23
【问题描述】:
我有一个函数:
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 是一个包含多个静态方法的类。这些方法作为字符串存储在 CardData 对象中。我提供了一个使用 OnTurnStarted 回调的示例。每次我想添加另一个回调时,重复写出所有这些代码是非常笨拙的。我试过创建一个函数:
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;
}
}
但是,where TDelegate : Delegate 不起作用。我不能只在方法中进行一些类型检查(即:
if(typeof(TDelegate).IsSubclassOf(typeof(Delegate)) == false)
{
throw new InvalidOperationException("Card::SetupCallback - " + typeof(TDelegate).Name + " is not a delegate");
}
因为delagateToAddThisTo属于TDelegate类型,需要能够添加。
提前谢谢你。
【问题讨论】:
-
我猜你意识到即使你让它工作了,
delagateToAddThisTo += t也没有任何效果。对于事件,+=被转换为add方法,对于委托,delagateToAddThisTo必须是一个变量(即ref)
标签: c# generics unity3d delegates action