How can you use optional parameters in C#?

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

    From this site:

    http://www.tek-tips.com/viewthread.cfm?qid=1500861&page=1

    C# does allow the use of the [Optional] attribute (from VB, though not functional in C#). So you can have a method like this:

    using System.Runtime.InteropServices;
    public void Foo(int a, int b, [Optional] int c)
    {
      ...
    }
    

    In our API wrapper, we detect optional parameters (ParameterInfo p.IsOptional) and set a default value. The goal is to mark parameters as optional without resorting to kludges like having "optional" in the parameter name.

提交回复
热议问题