如何通过反射执行带有可选参数的私有静态方法? [英] How to execute a private static method with optional parameters via reflection?

查看:117
本文介绍了如何通过反射执行带有可选参数的私有静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有可选参数的私有静态方法的类.如何通过反射从另一个类调用它?有一个类似的问题,但不涉及静态方法或可选参数.

I have a class with a private static method with an optional parameter. How do I invoke it from another class via Reflection? There is a similar question, but it does not address static method or optional parameters.

public class Foo {
    private static void Bar(string key = "") {
       // do stuff
    }
}

如何调用 Foo.Bar("test")Foo.Bar()(例如,不传递可选参数)?

How do I invoke Foo.Bar("test") and Foo.Bar() (e.g. without passing the optional parameter)?

推荐答案

C# 中的可选参数值是通过在调用点注入这些值来编译的.IE.即使您的代码是

Optional parameter values in C# are compiled by injection those values at the callsite. I.e. even though your code is

Foo.Bar()

编译器实际上会生成一个类似

The compiler actually generates a call like

Foo.Bar("")

在查找方法时,您需要将可选参数视为常规参数.

When finding the method you need to treat the optional parameters as regular parameters.

var method = typeof(Foo).GetMethod("Bar", BindingFlags.Static | BindingFlags.NonPublic);

如果您确切知道要使用哪些值调用该方法,则可以执行以下操作:

If you know exactly what values you want to invoke the method with you can do:

method.Invoke(obj: null, parameters: new object[] { "Test" });

如果您只有一些参数并希望遵守默认参数的值,则必须检查该方法的 ParameterInfo 对象以查看参数是否可选以及这些值是什么.例如,要打印出这些参数的默认值,您可以使用以下代码:

If you only have some of the parameters and want to honor the values of the default ones you have to inspect the method's ParameterInfo objects to see if the parameters are optional and what those values are. For example to print out the default values of those parameters you could use the following code:

foreach (ParameterInfo pi in method.GetParameters())
{
    if (pi.IsOptional)
    {
        Console.WriteLine(pi.Name + ": " + pi.DefaultValue);
    }
}

这篇关于如何通过反射执行带有可选参数的私有静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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