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

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

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


当前回答

而不是默认参数,为什么不直接从传入的querystring构造一个字典类..一个几乎与asp.net表单处理查询字符串的方式相同的实现。

即请求。查询字符串(“a”)

这将使叶子类与工厂/样板代码解耦。


您可能还想使用ASP.NET检查Web服务。Web服务是通过c#类的属性自动生成的Web api。

其他回答

从这个网站:

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

您可以使用default。

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

在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
}

在默认值不可用的情况下,添加可选参数的方法是使用.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);
        }

    }
}

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

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