How can you use optional parameters in C#?

前端 未结 23 2306
逝去的感伤
逝去的感伤 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:51

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

    0 讨论(0)
  • 2020-11-22 17:53

    You can use optional parameters in C# 4.0 without any worries. If we have a method like:

    int MyMetod(int param1, int param2, int param3=10, int param4=20){....}
    

    when you call the method, you can skip parameters like this:

    int variab = MyMethod(param3:50; param1:10);
    

    C# 4.0 implements a feature called "named parameters", you can actually pass parameters by their names, and of course you can pass parameters in whatever order you want :)

    0 讨论(0)
  • 2020-11-22 17:53

    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;
    }
    
    0 讨论(0)
  • 2020-11-22 17:55

    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.

    0 讨论(0)
  • 2020-11-22 17:55

    Instead of default parameters, why not just construct a dictionary class from the querystring passed .. an implementation that is almost identical to the way asp.net forms work with querystrings.

    i.e. Request.QueryString["a"]

    This will decouple the leaf class from the factory / boilerplate code.


    You also might want to check out Web Services with ASP.NET. Web services are a web api generated automatically via attributes on C# classes.

    0 讨论(0)
提交回复
热议问题