【问题标题】:Creating a Delegate from methodInfo in Mono 2.8.2在 Mono 2.8.2 中从 methodInfo 创建一个委托
【发布时间】:2013-10-01 23:22:09
【问题描述】:

您好,我正在尝试在 Mono 2.8.2 中创建一个 messenger - Unity3d 使用的子集。我认为创建一个助手来在使用“订阅”属性装饰时自动订阅信使的方法会很不错。

我一直在为此摸不着头脑,并阅读了许多其他相关的堆栈问题,但没有解决我的问题。 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
}

【问题讨论】:

  • 您尝试订阅的方法的签名是什么?它有像void MyMethod(object arg) 这样的签名吗?
  • 正确。我已经更新了帖子。
  • mono 2.8 太老了,请升级到 3.2.3
  • @knocte:不是一个选项。 Unity 使用 Unity 使用的单声道版本(技术上这个 fork:github.com/Unity-Technologies/mono)就是这样。

标签: c# reflection delegates mono


【解决方案1】:

这是一个非静态方法,您没有提供目标对象。因此Delegate.CreateDelegate 将创建一个带有显式this 参数的“开放委托”。

由于需要 this 参数,它不再匹配签名。

【讨论】:

  • 我被一个问题缠住了,错过了显而易见的事情。我需要学会放下咖啡去和我的猫玩耍。
  • 已经很久了,但这个答案真的很有帮助。 (Action&lt;object&gt;)Delegate.CreateDelegate(typeof(Action&lt;object&gt;), **this**, methodInfo); 会成功的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-02
  • 2011-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多