How can you use optional parameters in C#?

前端 未结 23 2642
逝去的感伤
逝去的感伤 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: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;
    }
    

提交回复
热议问题