gpt4 book ai didi

c# - 从 Mono 2.8.2 中的 methodInfo 创建委托(delegate)

转载 作者:太空狗 更新时间:2023-10-29 23:08:10 30 4
gpt4 key购买 nike

您好,我正在尝试在 Mono 2.8.2 中创建一个信使 - 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
}

最佳答案

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

由于必需的 this 参数,它不再与签名匹配。

关于c# - 从 Mono 2.8.2 中的 methodInfo 创建委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19127633/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com