How can you use optional parameters in C#?

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

    A little late to the party, but I was looking for the answer to this question and ultimately figured out yet another way to do this. Declare the data types for the optional args of your web method to be type XmlNode. If the optional arg is omitted this will be set to null, and if it's present you can get is string value by calling arg.Value, i.e.,

    [WebMethod]
    public string Foo(string arg1, XmlNode optarg2)
    {
        string arg2 = "";
        if (optarg2 != null)
        {
            arg2 = optarg2.Value;
        }
        ... etc
    }
    

    What's also decent about this approach is the .NET generated home page for the ws still shows the argument list (though you do lose the handy text entry boxes for testing).

提交回复
热议问题