Calling a function using reflection that has a quot;paramsquot; parameter (MethodBase)(使用具有“参数的反射调用函数.参数(方法库))
问题描述
我有两个函数的 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.
这篇关于使用具有“参数"的反射调用函数.参数(方法库)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用具有“参数"的反射调用函数.参数(方法库)


基础教程推荐
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01