通过反思可选参数调用方法 [英] Invoking methods with optional parameters through reflection
问题描述
我使用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);
这篇关于通过反思可选参数调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!