gpt4 book ai didi

c# - 使用具有 "params"参数的反射调用函数 (MethodBase)

转载 作者:可可西里 更新时间:2023-11-01 08:36:45 25 4
gpt4 key购买 nike

我有两个函数的 MethodBases:

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

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

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

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

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

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

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

最佳答案

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

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

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);
}

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

关于c# - 使用具有 "params"参数的反射调用函数 (MethodBase),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6484651/

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