How can you use optional parameters in C#?

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

    You can try this too
    Type 1
    public void YourMethod(int a=0, int b = 0) { //some code }


    Type 2
    public void YourMethod(int? a, int? b) { //some code }

    0 讨论(0)
  • 2020-11-22 17:48

    I had to do this in a VB.Net 2.0 Web Service. I ended up specifying the parameters as strings, then converting them to whatever I needed. An optional parameter was specified with an empty string. Not the cleanest solution, but it worked. Just be careful that you catch all the exceptions that can occur.

    0 讨论(0)
  • 2020-11-22 17:48

    optional parameters are nothing but default parameters! i suggest you give both of them default parameters. GetFooBar(int a=0, int b=0) if you don't have any overloaded method, will result in a=0, b=0 if you don't pass any values,if you pass 1 value, will result in, passed value for a, 0 and if you pass 2 values 1st will be assigned to a and second to b.

    hope that answers your question.

    0 讨论(0)
  • 2020-11-22 17:49

    Another option is to use the params keyword

    public void DoSomething(params object[] theObjects)
    {
      foreach(object o in theObjects)
      {
        // Something with the Objects…
      }
    }
    

    Called like...

    DoSomething(this, that, theOther);
    
    0 讨论(0)
  • 2020-11-22 17:51

    Hello Optional World

    If you want the runtime to supply a default parameter value, you have to use reflection to make the call. Not as nice as the other suggestions for this question, but compatible with VB.NET.

    using System;
    using System.Runtime.InteropServices;
    using System.Reflection;
    
    namespace ConsoleApplication1
    {
        class Class1
        {
            public static void sayHelloTo(
                [Optional,
                DefaultParameterValue("world")] string whom)
            {
                Console.WriteLine("Hello " + whom);
            }
    
            [STAThread]
            static void Main(string[] args)
            {
                MethodInfo mi = typeof(Class1).GetMethod("sayHelloTo");
                mi.Invoke(null, new Object[] { Missing.Value });
            }
        }
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题