How can you use optional parameters in C#?

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

    For a larger number of optional parameters, a single parameter of Dictionary could be used with the ContainsKey method. I like this approach because it allows me to pass a List or a T individually without having to create a whole other method (nice if parameters are to be used as filters, for example).

    Example (new Dictionary() would be passed if no optional parameters are desired):

    public bool Method(string ParamA, Dictionary AddlParams) {
        if(ParamA == "Alpha" && (AddlParams.ContainsKey("foo") || AddlParams.ContainsKey("bar"))) {
            return true;
        } else {
            return false;
        }
    }
    

提交回复
热议问题