How can you use optional parameters in C#?

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

    An easy way which allows you to omit any parameters in any position, is taking advantage of nullable types as follows:

    public void PrintValues(int? a = null, int? b = null, float? c = null, string s = "")
    {
        if(a.HasValue)
            Console.Write(a);
        else
            Console.Write("-");
    
        if(b.HasValue)
            Console.Write(b);
        else
            Console.Write("-");
    
        if(c.HasValue)
            Console.Write(c);
        else
            Console.Write("-");
    
        if(string.IsNullOrEmpty(s)) // Different check for strings
            Console.Write(s);
        else
            Console.Write("-");
    }
    

    Strings are already nullable types so they don't need the ?.

    Once you have this method, the following calls are all valid:

    PrintValues (1, 2, 2.2f);
    PrintValues (1, c: 1.2f);
    PrintValues(b:100);
    PrintValues (c: 1.2f, s: "hello");
    PrintValues();
    

    When you define a method that way you have the freedom to set just the parameters you want by naming them. See the following link for more information on named and optional parameters:

    Named and Optional Arguments (C# Programming Guide) @ MSDN

提交回复
热议问题