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

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

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


当前回答

我同意stephenbayer的观点。但由于它是一个webservice,对于最终用户来说,只使用一种形式的webmethod要比使用相同方法的多个版本更容易。我认为在这种情况下,可空类型是可选参数的完美选择。

public void Foo(int a, int b, int? c)
{
  if(c.HasValue)
  {
    // do something with a,b and c
  }
  else
  {
    // do something with a and b only
  }  
}

其他回答

您可以使用default。

public void OptionalParameters(int requerid, int optinal = default){}

从这个网站:

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”。

我同意stephenbayer的观点。但由于它是一个webservice,对于最终用户来说,只使用一种形式的webmethod要比使用相同方法的多个版本更容易。我认为在这种情况下,可空类型是可选参数的完美选择。

public void Foo(int a, int b, int? c)
{
  if(c.HasValue)
  {
    // do something with a,b and c
  }
  else
  {
    // do something with a and b only
  }  
}

你也可以试试这个 1型 你的方法(int a=0, int b =0) { / /一些代码 }

2型 你的方法(int?一个,int ?b) { / /一些代码 }

可选世界

如果希望运行时提供默认参数值,则必须使用反射进行调用。虽然没有这个问题的其他建议那么好,但是与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 });
       }
    }
}