注意:这个问题是在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#语言不支持这一点。最好的方法是什么?
当前回答
正如stephen提到的,在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
}
}
可选参数只是默认参数! 我建议给它们都设置默认参数。 GetFooBar(int a=0, int b=0)如果你没有任何重载方法,将导致a=0,如果你不传递任何值,b=0,如果你传递1个值,将导致,a的传递值为0,如果你传递2个值,第一个将被分配给a,第二个分配给b。
希望这回答了你的问题。
正如stephen提到的,在c#中处理这个问题的典型方法是重载方法。通过创建具有不同参数的方法的多个版本,可以有效地创建可选参数。在具有较少参数的表单中,您通常会调用方法的表单,在调用该方法时使用所有参数设置默认值。
可选参数用于方法。如果你需要一个类的可选参数,你是:
using c# 4.0: use optional arguments in the constructor of the class, a solution i prefer, since it's closer to what is done with methods, so easier to remember. here's an example: class myClass { public myClass(int myInt = 1, string myString = "wow, this is cool: i can have a default string") { // do something here if needed } } using c# versions previous to c#4.0: you should use constructor chaining (using the :this keyword), where simpler constructors lead to a "master constructor". example: class myClass { public myClass() { // this is the default constructor } public myClass(int myInt) : this(myInt, "whatever") { // do something here if needed } public myClass(string myString) : this(0, myString) { // do something here if needed } public myClass(int myInt, string myString) { // do something here if needed - this is the master constructor } }
你可以使用方法重载…
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应用程序。