Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Delegate from methodInfo in Mono 2.8.2

Hi I am trying to create a messenger in Mono 2.8.2 - the subset used by Unity3d. I thought it would be nifty to create a helper to auto subscribe methods to the messenger when they are decorated with a "subscribe" attribute.

I've been scratching my head over this and have read many of the other related stack questions without a solution to my problem. 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);
        }

Any suggestions or work around would be appreciated.

Edit The method signature looks like :

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

Though, it was originally...

[Subscribe]
void OnTestMessage(TestMessage message){
  // Hello World
}
like image 610
user2085865 Avatar asked Oct 01 '13 23:10

user2085865


1 Answers

It's a non-static method and you didn't provide a target object. Therefore Delegate.CreateDelegate will create an "open delegate" with an explicit this argument.

Because of the required this argument, it no longer matches the signature.

like image 79
Ben Voigt Avatar answered Oct 24 '22 03:10

Ben Voigt