2013-10-01 8 views
5

Witam Próbuję utworzyć komunikator w Mono 2.8.2 - podzbiorze używanym przez Unity3d. Pomyślałem, że fajnie byłoby stworzyć pomocnika do automatycznego zasubskrybowania metod dla komunikatora, gdy są one ozdobione atrybutem "subscribe".Tworzenie Delegata z metody methodInfo w Mono 2.8.2

Podrapałem się w głowę i przeczytałem wiele innych powiązanych pytań na temat stosów bez rozwiązania mojego problemu. 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); 
     } 

Wszelkie sugestie lub praca będą mile widziane.

Edit Podpis metoda wygląda następująco:

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

Choć było pierwotnie ...

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

Jaki jest podpis metody, którą subskrybujesz? Czy ma sygnaturę 'void MyMethod (object arg)'? –

+0

Prawidłowo. Zaktualizowałem post. – user2085865

+1

mono 2.8 jest bardzo stary, proszę uaktualnić do wersji 3.2.3 – knocte

Odpowiedz

6

Jest to metoda niestatyczny a nie stanowić cel obiekt. Dlatego Delegate.CreateDelegate utworzy "otwartego delegata" z wyraźnym argumentem this.

Z powodu wymaganego argumentu this, nie pasuje on już do podpisu.

+0

Zostaję zakorkowany przez jakiś problem i tęsknię za oczywistością. Muszę się nauczyć odkładać kawę i bawić się z moim kotem. – user2085865

+1

Minęło dużo czasu, ale ta odpowiedź naprawdę pomaga. '(Działanie ) Delegate.CreateDelegate (typeof (działanie ), ** this **, methodInfo);' sprawi, że będzie to w porządku. –

Powiązane problemy