使用具有“参数"的反射调用函数.参数(方法库) [英] Calling a function using reflection that has a "params" parameter (MethodBase)

查看:28
本文介绍了使用具有“参数"的反射调用函数.参数(方法库)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个函数的 MethodBase:

I have MethodBases for two functions:

public static int Add(params int[] parameters) { /* ... */ }
public static int Add(int a, int b) { /* ... */ }

我有一个通过我创建的类调用 MethodBases 的函数:

I have a function that calls the MethodBases via a class I made:

MethodBase Method;
object Target;
public object call(params object[] input)
{
    return Method.Invoke(Target, input);
}

现在如果我 AddTwoMethod.call(5, 4); 它工作正常.

Now if I AddTwoMethod.call(5, 4); it works fine.

如果我使用 AddMethod.call(5, 4); 它会返回:

If I however use AddMethod.call(5, 4); it returns:

未处理的异常:System.Reflection.TargetParameterCountException:参数与签名不匹配

Unhandled Exception: System.Reflection.TargetParameterCountException: parameters do not match signature

有什么方法可以使两个调用都能正常工作,而无需手动将参数放入 params int[] 的数组中?

Is there any way to make it so that both calls work fine without need for manually putting the arguments in an array for the params int[]?

推荐答案

您可以修改您的 call 方法以检测 params 参数并将输入的其余部分转换为新数组.这样一来,您的方法的行为就与 C# 应用于方法调用的逻辑几乎相同.

You could modify your call method to detect the params parameter and convert the rest of the input to a new array. That way your method could act pretty much the same as the logic C# applies to the method calling.

我为您快速构建的东西(请注意,我以非常有限的方式测试了此方法,因此可能仍然存在错误):

Something i quicly constructed for you (be aware that i tested this method in a pretty limited way, so there might be errors still):

public object call(params object[] input)
{
    ParameterInfo[] parameters = Method.GetParameters();
    bool hasParams = false;
    if (parameters.Length > 0)
        hasParams = parameters[parameters.Length - 1].GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0;

    if (hasParams)
    {
        int lastParamPosition = parameters.Length - 1;

        object[] realParams = new object[parameters.Length];
        for (int i = 0; i < lastParamPosition; i++)
            realParams[i] = input[i];

        Type paramsType = parameters[lastParamPosition].ParameterType.GetElementType();
        Array extra = Array.CreateInstance(paramsType, input.Length - lastParamPosition);
        for (int i = 0; i < extra.Length; i++)
            extra.SetValue(input[i + lastParamPosition], i);

        realParams[lastParamPosition] = extra;

        input = realParams;
    }

    return Method.Invoke(Target, input);
}

请注意,我以非常有限的方式测试了此方法,因此可能仍然存在错误.

Be aware that i tested this method in a pretty limited way, so there might be errors still.

这篇关于使用具有“参数"的反射调用函数.参数(方法库)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆