注意:这个问题是在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#语言不支持这一点。最好的方法是什么?
当前回答
另一种选择是使用params关键字
public void DoSomething(params object[] theObjects)
{
foreach(object o in theObjects)
{
// Something with the Objects…
}
}
叫喜欢……
DoSomething(this, that, theOther);
其他回答
从这个网站:
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”。
可选参数用于方法。如果你需要一个类的可选参数,你是:
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 } }
我有一个web服务要写,需要7个参数。每个属性都是由此web服务包装的sql语句的可选查询属性。所以我想到了两个非可选参数的变通方法…都很穷:
方法1(param1, param2, param 3, param 4, param 5, param 6, param7) 方法1(param1, param2, param3, param4, param5, param 6) 方法1(param1, param2, param3, param4, param5, param7)…开始看图片。这就是疯狂。太多的组合了。
现在有一个看起来很尴尬但应该有效的更简单的方法: method1(param1, bool useParam1, param2, bool useParam2,等等…)
这是一个方法调用,所有参数的值都是必需的,它将处理其中的每种情况。如何从界面使用它也很清楚。
这是一个黑客,但它会起作用。
一个简单的方法可以让你省略任何位置的任何参数,就是利用可空类型,如下所示:
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
我必须在VB中完成。Net 2.0 Web服务。我最终将参数指定为字符串,然后将它们转换为我需要的任何参数。使用空字符串指定了可选参数。虽然不是最干净的方法,但很有效。只是要注意捕获所有可能发生的异常。