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

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

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


当前回答

使用重载或使用c# 4.0或更高版本

 private void GetVal(string sName, int sRoll)
 {
   if (sRoll > 0)
   {
    // do some work
   }
 }

 private void GetVal(string sName)
 {
    GetVal("testing", 0);
 }

其他回答

另一种选择是使用params关键字

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

叫喜欢……

DoSomething(this, that, theOther);

我同意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
  }  
}

在默认值不可用的情况下,添加可选参数的方法是使用.NET OptionalAttribute类- https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.optionalattribute?view=netframework-4.8

代码示例如下:

namespace OptionalParameterWithOptionalAttribute
{
    class Program
    {
        static void Main(string[] args)
        {
            //Calling the helper method Hello only with required parameters
            Hello("Vardenis", "Pavardenis");
            //Calling the helper method Hello with required and optional parameters
            Hello("Vardenis", "Pavardenis", "Palanga");
        }
        public static void Hello(string firstName, string secondName, 
            [System.Runtime.InteropServices.OptionalAttribute] string  fromCity)
        {
            string result = firstName + " " + secondName;
            if (fromCity != null)
            {
                result += " from " + fromCity;
            }
            Console.WriteLine("Hello " + result);
        }

    }
}

令人惊讶的是没有人提到c# 4.0的可选参数是这样工作的:

public void SomeMethod(int a, int b = 0)
{
   //some code
}

编辑:我知道在问这个问题的时候,c# 4.0还不存在。但是这个问题仍然在谷歌的“c#可选参数”中排名第一,所以我认为-这个答案值得在这里。对不起。

在c#中,我通常会使用多种形式的方法:

void GetFooBar(int a) { int defaultBValue;  GetFooBar(a, defaultBValue); }
void GetFooBar(int a, int b)
{
 // whatever here
}

更新:上面提到的是我在c# 2.0中处理默认值的方式。我现在工作的项目使用c# 4.0,现在直接支持可选参数。下面是我在自己的代码中使用的一个例子:

public EDIDocument ApplyEDIEnvelop(EDIVanInfo sender, 
                                   EDIVanInfo receiver, 
                                   EDIDocumentInfo info,
                                   EDIDocumentType type 
                                     = new EDIDocumentType(EDIDocTypes.X12_814),
                                   bool Production = false)
{
   // My code is here
}