【发布时间】: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