通过反射调用带有可选参数的方法 [英] 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?
这是我现在使用的代码:
Here is the code I use now:
type.GetParameterlessConstructor()
.Invoke(BindingFlags.OptionalParamBinding |
BindingFlags.InvokeMethod |
BindingFlags.CreateInstance,
null,
new object[0],
CultureInfo.InvariantCulture);
(我刚刚尝试了不同的 BindingFlags
).
(I've just tried with different BindingFlags
).
GetParameterlessConstructor
是我为 Type
编写的自定义扩展方法.
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屋!