How to pass a method with optional parameters as an argument?

前提是你 提交于 2019-12-06 08:19:20

So, the question is: can I somehow pass a method with an optional parameter as an argument without explicitly declaring a delegate and keep the optional quality of its parameters?

No. The "optionality" is part of the signature of the method, which the compiler needs to know at at compile time to provide the default value. If you're using a delegate type that doesn't have the optional parameter, what is the compiler meant to do when you try to call it without enough arguments?

The simplest approach is probably to wrap it:

CallMethod(() => Foo()); // Compiler will use default within the lambda.
...
public void Foo(bool x = true) { ... }

public void CallMethod(Action action) { ... }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!