在带有可选参数的函数上使用 Reflector.Invoke 方法
我正在尝试使用 Reflector.InvokeMethod 来调用带有可选参数的函数。 该函数看起来像这样:
Private Function DoSomeStuff(ByVal blah1 as string, ByVal blah2 as string, Optional ByVal blah3 as string = "45") as boolean
'stuff
end function
我像这样调用它:
Dim result As Boolean = Reflector.InvokeMethod(AccessModifier.private,obj_of_Class, "DoSomeStuff", Param1, Param2, Param3)
这工作正常,除了当我不传递第三个(可选)参数时,它不会命中该函数。
Dim result As Boolean = Reflector.InvokeMethod(AccessModifier.private,obj_of_Class, "DoSomeStuff", Param1, Param2)
有没有办法可以使用 Reflector.invokeMethod 来调用此函数而不传递可选参数? 或者另一种方式来实现这一目标?
I am trying to use reflector.InvokeMethod to invoke a function with an optional parameter.
The function looks like this:
Private Function DoSomeStuff(ByVal blah1 as string, ByVal blah2 as string, Optional ByVal blah3 as string = "45") as boolean
'stuff
end function
and I'm Invoking it like this:
Dim result As Boolean = Reflector.InvokeMethod(AccessModifier.private,obj_of_Class, "DoSomeStuff", Param1, Param2, Param3)
This works fine, other than when I don't pass the third (optional) parameter, it dosn't hit the function.
Dim result As Boolean = Reflector.InvokeMethod(AccessModifier.private,obj_of_Class, "DoSomeStuff", Param1, Param2)
Is there a way I can use Reflector.invokeMethod to call this function without passing the optional parameter? or another way to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Visual Basic 编译器实际上将可选参数值替换到调用代码中。 因此,如果您的实际代码是:
Visual Basic 将发出相当于以下内容的 IL 代码:
要知道最后一个参数是什么,您需要获取对参数对象的引用(我不确定 Reflector 中的对象是什么) .NET 中,您可以访问 MethodInfo,然后访问 ParameterInfo),然后获取其自定义属性,查找标有OptionalAttribute 和 DefaultParameterValueAttribute 的属性。 然后,您需要使用第三个参数调用它,并提供 DefaultParameterValueAttribute 中的值。
The Visual Basic compiler actually substitutes the optional parameter values into the calling code. So if your actual code was:
Visual Basic would have emitted IL code equivalent to:
To know what that last parameter is, you'll need to get a reference to the parameter's object (I'm not sure what that is in Reflector - in .NET you'd get access to the MethodInfo and then to the ParameterInfo), then get its custom attributes, looking for an attribute marked with OptionalAttribute and DefaultParameterValueAttribute. Then, you'll need to call it with the third parameter, supplying the value from DefaultParameterValueAttribute.
我会重载 DoSomeStuff 方法,而不是使用可选参数...
I would overload the DoSomeStuff method rather than use an optional parameter...