检查 `object[] args` 是否满足 Delegate 实例?

发布于 2024-08-14 16:00:33 字数 413 浏览 3 评论 0原文

我有以下方法签名:

public static void InvokeInFuture(Delegate method, params object[] args)
{
    // ...
}

委托和参数保存到集合中以供将来调用。

有什么方法可以检查参数数组是否满足委托要求而不调用它?

谢谢。

编辑: 感谢您的反射实现,但我正在寻找一种内置的方法来执行此操作。我不想倒转轮子,.NET Framework 已经在 Delegate.DynamicInvoke() 的某个地方实现了这种检查,该实现可以处理只有 Microsoft 开发人员才能考虑的所有那些疯狂的特殊情况,并通过了单元测试和 QA。有什么办法可以使用这个内置实现吗?

谢谢。

I have the following method signature:

public static void InvokeInFuture(Delegate method, params object[] args)
{
    // ...
}

The delegate and the arguments are saved to a collection for future invoking.

Is there any way i can check whether the arguments array satisfies the delegate requirements without invoking it?

Thanks.

EDIT:
Thanks for the reflection implementation, but i searching for a built-in way to do this. I don't want to reinvert the wheel, the .NET Framework already have this checking implemented inside Delegate.DynamicInvoke() somewhere, implementation that handles all those crazy special cases that only Microsoft's developers can think about, and passed Unit Testing and QA. Is there any way to use this built-in implementation?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心房敞 2024-08-21 16:00:33

您可以使用反射来获取委托的方法签名,如下所示。

using System;
using System.Reflection;

bool ValidateDelegate(Delegate method, params object[] args)
{
    ParameterInfo[] parameters = method.Method.GetParameters();
    if (parameters.Length != args.Length) { return false; }

    for (int i = 0; i < parameters.Length; ++i)
    {
        if (parameters[i].ParameterType.IsValueType && args[i] == null ||
            !parameters[i].ParameterType.IsAssignableFrom(args[i].GetType()))
        {
            return false;
        }
    }

    return true;
}

You can use reflection to get the method signature of the delegate as follows.

using System;
using System.Reflection;

bool ValidateDelegate(Delegate method, params object[] args)
{
    ParameterInfo[] parameters = method.Method.GetParameters();
    if (parameters.Length != args.Length) { return false; }

    for (int i = 0; i < parameters.Length; ++i)
    {
        if (parameters[i].ParameterType.IsValueType && args[i] == null ||
            !parameters[i].ParameterType.IsAssignableFrom(args[i].GetType()))
        {
            return false;
        }
    }

    return true;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文