How can you use optional parameters in C#?

前端 未结 23 2281
逝去的感伤
逝去的感伤 2020-11-22 17:02

Note: This question was asked at a time when C# did not yet support optional parameters (i.e. before C# 4).

We\'re building a web API tha

23条回答
  •  清酒与你
    2020-11-22 17:42

    I have a web service to write that takes 7 parameters. Each is an optional query attribute to a sql statement wrapped by this web service. So two workarounds to non-optional params come to mind... both pretty poor:

    method1(param1, param2, param 3, param 4, param 5, param 6, param7) method1(param1, param2, param3, param 4, param5, param 6) method 1(param1, param2, param3, param4, param5, param7)... start to see the picture. This way lies madness. Way too many combinations.

    Now for a simpler way that looks awkward but should work: method1(param1, bool useParam1, param2, bool useParam2, etc...)

    That's one method call, values for all parameters are required, and it will handle each case inside it. It's also clear how to use it from the interface.

    It's a hack, but it will work.

提交回复
热议问题