注意:这个问题是在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#语言不支持这一点。最好的方法是什么?
当前回答
从这个网站:
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”。
其他回答
你也可以试试这个 1型 你的方法(int a=0, int b =0) { / /一些代码 }
2型 你的方法(int?一个,int ?b) { / /一些代码 }
在默认值不可用的情况下,添加可选参数的方法是使用.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中使用可选参数。 如果我们有这样一个方法:
int MyMetod(int param1, int param2, int param3=10, int param4=20){....}
当你调用这个方法时,你可以像这样跳过参数:
int variab = MyMethod(param3:50; param1:10);
c# 4.0实现了一个叫做“命名参数”的特性,你实际上可以通过参数的名字来传递参数,当然你可以按照你想要的任何顺序来传递参数:)
正如stephen提到的,在c#中处理这个问题的典型方法是重载方法。通过创建具有不同参数的方法的多个版本,可以有效地创建可选参数。在具有较少参数的表单中,您通常会调用方法的表单,在调用该方法时使用所有参数设置默认值。
对于大量的可选参数,可以使用ContainsKey方法使用Dictionary<string,Object>的单个参数。我喜欢这种方法,因为它允许我单独传递List<T>或T,而不必创建一个完整的其他方法(例如,如果参数要用作过滤器,那就很好了)。
示例(如果不需要可选参数,则传递new Dictionary<string,Object>()):
public bool Method(string ParamA, Dictionary<string,Object> AddlParams) {
if(ParamA == "Alpha" && (AddlParams.ContainsKey("foo") || AddlParams.ContainsKey("bar"))) {
return true;
} else {
return false;
}
}