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

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

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


当前回答

我必须在VB中完成。Net 2.0 Web服务。我最终将参数指定为字符串,然后将它们转换为我需要的任何参数。使用空字符串指定了可选参数。虽然不是最干净的方法,但很有效。只是要注意捕获所有可能发生的异常。

其他回答

使用重载或使用c# 4.0或更高版本

 private void GetVal(string sName, int sRoll)
 {
   if (sRoll > 0)
   {
    // do some work
   }
 }

 private void GetVal(string sName)
 {
    GetVal("testing", 0);
 }

可选参数用于方法。如果你需要一个类的可选参数,你是:

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

对于大量的可选参数,可以使用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;
    }
}

令人惊讶的是没有人提到c# 4.0的可选参数是这样工作的:

public void SomeMethod(int a, int b = 0)
{
   //some code
}

编辑:我知道在问这个问题的时候,c# 4.0还不存在。但是这个问题仍然在谷歌的“c#可选参数”中排名第一,所以我认为-这个答案值得在这里。对不起。

虽然有点晚了,但我一直在寻找这个问题的答案,并最终找到了另一种方法。将web方法的可选参数的数据类型声明为XmlNode类型。如果可选的arg被省略,它将被设置为空,如果它存在,你可以通过调用arg来获取它的字符串值。值,即

[WebMethod]
public string Foo(string arg1, XmlNode optarg2)
{
    string arg2 = "";
    if (optarg2 != null)
    {
        arg2 = optarg2.Value;
    }
    ... etc
}

这种方法的另一个优点是。net为ws生成的主页仍然显示参数列表(尽管您确实失去了用于测试的方便文本输入框)。