问题描述
我有两个函数的 MethodBase:
I have MethodBases for two functions:
public static int Add(params int[] parameters) { /* ... */ }
public static int Add(int a, int b) { /* ... */ }
我有一个通过我创建的类调用 MethodBase 的函数:
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:参数与签名不匹配
有什么方法可以让两个调用都正常工作,而无需手动将参数放入 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.
这篇关于使用具有“params"的反射调用函数参数(方法库)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!