注意:这个问题是在c#还不支持可选参数的时候提出的(即在c# 4之前)。

我们正在构建一个web API,它是从c#类中编程生成的。该类有方法GetFooBar(int a, int b), API有方法GetFooBar接受查询参数,如&a=foo &b=bar。

类需要支持可选参数,而c#语言不支持这一点。最好的方法是什么?


当前回答

为了以防万一,如果有人想传递一个回调(或委托)作为可选参数,可以这样做。

可选回调参数:

public static bool IsOnlyOneElement(this IList lst, Action callbackOnTrue = (Action)((null)), Action callbackOnFalse = (Action)((null)))
{
    var isOnlyOne = lst.Count == 1;
    if (isOnlyOne && callbackOnTrue != null) callbackOnTrue();
    if (!isOnlyOne && callbackOnFalse != null) callbackOnFalse();
    return isOnlyOne;
}

其他回答

可选世界

如果希望运行时提供默认参数值,则必须使用反射进行调用。虽然没有这个问题的其他建议那么好,但是与VB.NET兼容。

using System;
using System.Runtime.InteropServices;
using System.Reflection;

namespace ConsoleApplication1
{
   public class Class1
    {
        public static void SayHelloTo([Optional, DefaultParameterValue("world")] string whom)
        {
            Console.WriteLine("Hello " + whom);
        }

       [STAThread]
       public static void Main(string[] args)
       {
            MethodInfo mi = typeof(Class1).GetMethod("sayHelloTo");
            mi.Invoke(null, new Object[] { Missing.Value });
       }
    }
}

一个简单的方法可以让你省略任何位置的任何参数,就是利用可空类型,如下所示:

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

字符串已经是可空类型,所以它们不需要?。

一旦你有了这个方法,下面的调用都是有效的:

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

当您以这种方式定义一个方法时,您可以通过命名来自由地设置您想要的参数。有关命名参数和可选参数的更多信息,请参阅以下链接:

命名和可选参数(c#编程指南)@ MSDN

从这个网站:

https://www.tek-tips.com/viewthread.cfm?qid=1500861

c#确实允许使用[Optional]属性(来自VB,但在c#中没有功能)。你可以有一个这样的方法:

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

在我们的API包装器中,我们检测可选参数(ParameterInfo p.s isoptional)并设置默认值。我们的目标是将参数标记为可选的,而不是在参数名称中使用“optional”。

可选参数只是默认参数! 我建议给它们都设置默认参数。 GetFooBar(int a=0, int b=0)如果你没有任何重载方法,将导致a=0,如果你不传递任何值,b=0,如果你传递1个值,将导致,a的传递值为0,如果你传递2个值,第一个将被分配给a,第二个分配给b。

希望这回答了你的问题。

为了以防万一,如果有人想传递一个回调(或委托)作为可选参数,可以这样做。

可选回调参数:

public static bool IsOnlyOneElement(this IList lst, Action callbackOnTrue = (Action)((null)), Action callbackOnFalse = (Action)((null)))
{
    var isOnlyOne = lst.Count == 1;
    if (isOnlyOne && callbackOnTrue != null) callbackOnTrue();
    if (!isOnlyOne && callbackOnFalse != null) callbackOnFalse();
    return isOnlyOne;
}