问题描述
我有两个功能MethodBases:
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 );
正常工作
如果我使用,无论 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[]
?
推荐答案
您可以修改呼叫
法检测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.
这是我为你quicly构造(注意,我在测试这种方法一个非常有限的方式,所以有可能是仍然错误):
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"参数(MethodBase)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!