如何通过反射为参数的默认值调用方法的方法 [英] How invoke method for a method by default value for parameters by reflection

查看:33
本文介绍了如何通过反射为参数的默认值调用方法的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须通过默认值参数来调用方法.通过此消息,它具有 TargetParameterCountException :参数计数不匹配

I have need to invoke a method by default value parameters. It has a TargetParameterCountException by this message : Parameter count mismatch

var methodName = "MyMethod";
var params = new[] { "Param 1"};

var method = typeof(MyService).GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic);
method.Invoke(method.IsStatic ? null : this, params);

private void MyMethod(string param1, string param2 = null)
{
}

为什么?我该如何通过反射来调用此方法以获取参数的默认值?

Why? How can I invoke this method by reflection for default value for parameters?

推荐答案

您可以使用 ParameterInfo.DefaultValue 进行检测.您需要检查给定的参数数量是否等于方法中的参数数量,然后找到具有默认值的参数并提取这些默认值.

You can use ParameterInfo.HasDefaultValue and ParameterInfo.DefaultValue to detect this. You'd need to check whether the number of arguments you've been given is equal to the number of parameters in the method, and then find the ones with default values and extract those default values.

例如:

var parameters = method.GetParameters();
object[] args = new object[parameters.Length];
for (int i = 0; i < args.Length; i++)
{
    if (i < providedArgs.Length)
    {
        args[i] = providedArgs[i];
    }
    else if (parameters[i].HasDefaultValue)
    {
        args[i] = parameters[i].DefaultValue;
    }
    else
    {
        throw new ArgumentException("Not enough arguments provided");
    }
}
method.Invoke(method.IsStatic ? null : this, args);

这篇关于如何通过反射为参数的默认值调用方法的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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