注意:这个问题是在c#还不支持可选参数的时候提出的(即在c# 4之前)。
我们正在构建一个web API,它是从c#类中编程生成的。该类有方法GetFooBar(int a, int b), API有方法GetFooBar接受查询参数,如&a=foo &b=bar。
类需要支持可选参数,而c#语言不支持这一点。最好的方法是什么?
注意:这个问题是在c#还不支持可选参数的时候提出的(即在c# 4之前)。
我们正在构建一个web API,它是从c#类中编程生成的。该类有方法GetFooBar(int a, int b), API有方法GetFooBar接受查询参数,如&a=foo &b=bar。
类需要支持可选参数,而c#语言不支持这一点。最好的方法是什么?
当前回答
在默认值不可用的情况下,添加可选参数的方法是使用.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);
}
}
}
其他回答
在默认值不可用的情况下,添加可选参数的方法是使用.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);
}
}
}
您可以使用default。
public void OptionalParameters(int requerid, int optinal = default){}
你可以重载你的方法。一个方法包含一个参数GetFooBar(int a),另一个包含两个参数GetFooBar(int a, int b)
你可以使用方法重载…
GetFooBar() GetFooBar(int a) GetFooBar(int a, int b)
这取决于方法的签名,我给出的例子缺少“int b”方法,因为它将具有与“int a”方法相同的签名。
你可以使用Nullable类型…
GetFooBar(int? a, int? b)
然后,您可以使用a. hasvalue检查是否设置了参数。
另一种选择是使用'params'参数。
GetFooBar(params object[] args)
如果你想要使用命名参数,就需要创建一个类型来处理它们,尽管我认为已经有一些这样的web应用程序。
而不是默认参数,为什么不直接从传入的querystring构造一个字典类..一个几乎与asp.net表单处理查询字符串的方式相同的实现。
即请求。查询字符串(“a”)
这将使叶子类与工厂/样板代码解耦。
您可能还想使用ASP.NET检查Web服务。Web服务是通过c#类的属性自动生成的Web api。