How can you use optional parameters in C#?

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

    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 });
            }
        }
    }
    

提交回复
热议问题