How can you use optional parameters in C#?

2019-01-01 05:17发布

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 that's programmatically generated from a C# class. The class has method GetFooBar(int a, int b) and the API has a method GetFooBar taking query params like &a=foo &b=bar.

The classes needs to support optional parameters, which isn't supported in C# the language. What's the best approach?

19条回答
大哥的爱人
2楼-- · 2019-01-01 05:32

You can overload your method. One method contains one parameter GetFooBar(int a) and the other contain both parameters, GetFooBar(int a, int b)

查看更多
余欢
3楼-- · 2019-01-01 05:33

For just in case if someone wants to pass a callback (or delegate) as an optional parameter, can do it this way.

Optional Callback parameter:

public static bool IsOnlyOneElement(this IList lst, Action callbackOnTrue = (Action)((null)), Action callbackOnFalse = (Action)((null)))
{
    var isOnlyOne = lst.Count == 1;
    if (isOnlyOne && callbackOnTrue != null) callbackOnTrue();
    if (!isOnlyOne && callbackOnFalse != null) callbackOnFalse();
    return isOnlyOne;
}
查看更多
人间绝色
4楼-- · 2019-01-01 05:33

You can try this too
Type 1
public void YourMethod(int a=0, int b = 0) { //some code }


Type 2
public void YourMethod(int? a, int? b) { //some code }

查看更多
明月照影归
5楼-- · 2019-01-01 05:35

The typical way this is handled in C# as stephen mentioned is to overload the method. By creating multiple versions of the method with different parameters you effectively create optional parameters. In the forms with fewer parameters you would typically call the form of the method with all of the parameters setting your default values in the call to that method.

查看更多
与君花间醉酒
6楼-- · 2019-01-01 05:36

In C#, I would normally use multiple forms of the method:

void GetFooBar(int a) { int defaultBValue;  GetFooBar(a, defaultBValue); }
void GetFooBar(int a, int b)
{
 // whatever here
}

UPDATE: This mentioned above WAS the way that I did default values with C# 2.0. The projects I'm working on now are using C# 4.0 which now directly supports optional parameters. Here is an example I just used in my own code:

public EDIDocument ApplyEDIEnvelop(EDIVanInfo sender, 
                                   EDIVanInfo receiver, 
                                   EDIDocumentInfo info,
                                   EDIDocumentType type 
                                     = new EDIDocumentType(EDIDocTypes.X12_814),
                                   bool Production = false)
{
   // My code is here
}
查看更多
余生请多指教
7楼-- · 2019-01-01 05:36

I had to do this in a VB.Net 2.0 Web Service. I ended up specifying the parameters as strings, then converting them to whatever I needed. An optional parameter was specified with an empty string. Not the cleanest solution, but it worked. Just be careful that you catch all the exceptions that can occur.

查看更多
登录 后发表回答