简体   繁体   English

如何使用反射调用带有可选参数的方法 c#

[英]How to call Method with optional parameters using reflections c#

I'm calling a methods using reflections.我正在调用使用反射的方法。 However due to some requirement one of the method parameters are changed and keeping new parameters as optional parameters.但是,由于某些要求,方法参数之一已更改,并将新参数保留为可选参数。 here is code这是代码

Void Method1(string request, string constants, string count = null)

Void Method2(string request, string constants)

In Method1 count parameter is optional .For the above methods, I'm calling using reflections Here is the code:在 Method1 中的 count 参数是可选的。对于上述方法,我使用反射调用这里是代码:

result = methodInfo.Invoke(classInstance, new object[] {request, constants});

I have tried with below approach but getting exception我尝试过以下方法但遇到异常

result = methodInfo.Invoke(classInstance, new object[] {request, constants ,System.Type.Missing});

Got below exception for Method2 the above code is working for Method1得到了Method2的异常,上面的代码适用于Method1

Parameter count mismatch.参数计数不匹配。

Please suggest me for optional parameters in method using reflections请向我建议使用反射的方法中的可选参数

Thanks in Advance!提前致谢!

Optional parameters: aren't actually optional - all that happens is that the compiler normally supplies the omitted value automatically for you.可选参数:实际上不是可选的——所发生的只是编译器通常会自动为您提供省略的值。 Since you're not using a compiler here, you'll need to supply it yourself, using new object[] {request, constants, null} .由于您在这里没有使用编译器,因此您需要自己提供它,使用new object[] {request, constants, null} Note that if you want to properly respect the default value (rather than knowing it is null in this case), you'd need to look at the ParameterInfo , specifically .HasDefaultValue and .DefaultValue .请注意,如果您想正确尊重默认值(而不是在这种情况下知道它是null ),您需要查看ParameterInfo ,特别是.HasDefaultValue.DefaultValue

Example (not using ParameterInfo , note):示例(不使用ParameterInfo ,注意):

using System;
using System.Reflection;

class P
{
    static void Main()
    {
        string request = "r", constants = "c", count = "#";
        var classInstance = new P();

        typeof(P).GetMethod(nameof(Method1),
            BindingFlags.Instance | BindingFlags.NonPublic)
            .Invoke(classInstance, new object[] { request, constants, null });

        typeof(P).GetMethod(nameof(Method1),
            BindingFlags.Instance | BindingFlags.NonPublic)
            .Invoke(classInstance, new object[] { request, constants, count });

        typeof(P).GetMethod(nameof(Method2),
            BindingFlags.Instance | BindingFlags.NonPublic)
            .Invoke(classInstance, new object[] { request, constants });
    }

    void Method1(string request, string constants, string count = null)
        => Console.WriteLine($"#1: {request}, {constants}, {count}");

    void Method2(string request, string constants)
        => Console.WriteLine($"#2: {request}, {constants}");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM