我有一個函數:C#的委託類型作爲通用的限制
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和需要能夠被添加到
預先感謝您
我想你會意識到,即使你讓它工作,'d elagateToAddThisTo + = t'將不起作用。對於事件'+ ='被轉換爲'add'方法,並且對於代表'delagateToAddThisTo'必須是變量(即'ref') –