通过反思可选参数调用方法可选、参数、方法

2023-09-02 10:26:47 作者:一身撩妹味

我使用C#4.0中使用可选参数运行到另外一个问题。

I've run into another problem using C# 4.0 with optional parameters.

我如何调用一个函数(或者更确切地说,构造,我有 ConstructorInfo 对象),我知道它不需要任何参数?

How do I invoke a function (or rather a constructor, I have the ConstructorInfo object) for which I know it doesn't require any parameters?

下面是code我现在用的:

Here is the code I use now:

type.GetParameterlessConstructor()
    .Invoke(BindingFlags.OptionalParamBinding | 
            BindingFlags.InvokeMethod | 
            BindingFlags.CreateInstance, 
            null, 
            new object[0], 
            CultureInfo.InvariantCulture);

(我只是尝试了不同的的BindingFlags )。

GetParameterlessConstructor 是一个自定义的扩展方法我写了键入

GetParameterlessConstructor is a custom extension method I wrote for Type.

推荐答案

根据 MSDN ,使用默认参数,你应该通过 Type.Missing

According to MSDN, to use the default parameter you should pass Type.Missing.

如果您的构造函数传递一个空对象数组的三个可选参数,然后代替你传递一个三元素对象数组,其中每个元素的值是 Type.Missing ,例如:

If your constructor has three optional arguments then instead of passing an empty object array you'd pass a three element object array where each element's value is Type.Missing, e.g.

type.GetParameterlessConstructor()
    .Invoke(BindingFlags.OptionalParamBinding | 
            BindingFlags.InvokeMethod | 
            BindingFlags.CreateInstance, 
            null, 
            new object[] { Type.Missing, Type.Missing, Type.Missing }, 
            CultureInfo.InvariantCulture);
 
精彩推荐
图片推荐