2013-10-01 28 views
5

嗨我正在嘗試在Mono 2.8.2中創建一個Messenger - Unity3d使用的子集。我認爲在用「subscribe」屬性裝飾時,創建一個幫助器來自動訂閱方法給Messenger時會很好用。在Mono 2.8.2中創建一個來自methodInfo的委託

我一直在撓撓我的頭,並閱讀了很多其他相關的堆棧問題,而沒有解決我的問題。 Frankly, I don't know if I am doing something wrong or if this is a bug in Mono.

foreach (var methodInfo in methods) 
     { 
      var attr = methodInfo.GetAttribute<SubscribeAttribute>(); 
      if (attr == null) 
       continue; 

      var parmas = methodInfo.GetParameters(); 
      if (parmas.Length != 1) 
      { 
       Debug.LogError("Subscription aborted. Invalid paramters."); 
       continue; 
      } 

      var type = parmas[0].ParameterType; 

      // Crashes here 
      // ArgumentException: method argument length mismatch 
      // I have tried many combinations.. 
      // Direct typing of the message type and dynamic typing 

      var action = (Action<object>)Delegate.CreateDelegate(typeof(Action<object>), methodInfo); 

      // also does not work 
      // var dt = Expression.GetActionType(parmas.Select(o => o.ParameterType).ToArray()); 
      // var action = Delegate.CreateDelegate(dt, methodInfo); 

      Subscribe(type, action, instance); 
     } 

任何建議或變通,將不勝感激。

編輯 方法簽名是這樣的:

[Subscribe] 
void OnMessage(object message){ 
    // Hello World 
} 

雖然,它最初是...

[Subscribe] 
void OnTestMessage(TestMessage message){ 
    // Hello World 
} 
+0

您試圖訂閱的方法的簽名是什麼?它是否有像'void MyMethod(object arg)'這樣的簽名? –

+0

正確。我已更新該帖子。 – user2085865

+1

單聲道2.8是非常古老的,請升級到3.2.3 – knocte

回答

6

這是一個非靜態方法,並且沒有提供目標目的。因此Delegate.CreateDelegate將創建一個明確的this參數的「公開委託」。

由於所需的this參數,它不再匹配簽名。

+0

我讓自己在一個問題上結束了,並且錯過了顯而易見的事實。我需要學習放下咖啡,然後和我的貓一起玩。 – user2085865

+1

已經很長時間了,但這個答案確實有幫助。 '(Action )Delegate.CreateDelegate(typeof(Action ),** this **,methodInfo);'會使它正確。 –