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

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

类需要支持可选参数,而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;
    }
}

其他回答

为了以防万一,如果有人想传递一个回调(或委托)作为可选参数,可以这样做。

可选回调参数:

public static bool IsOnlyOneElement(this IList lst, Action callbackOnTrue = (Action)((null)), Action callbackOnFalse = (Action)((null)))
{
    var isOnlyOne = lst.Count == 1;
    if (isOnlyOne && callbackOnTrue != null) callbackOnTrue();
    if (!isOnlyOne && callbackOnFalse != null) callbackOnFalse();
    return isOnlyOne;
}

可选世界

如果希望运行时提供默认参数值,则必须使用反射进行调用。虽然没有这个问题的其他建议那么好,但是与VB.NET兼容。

using System;
using System.Runtime.InteropServices;
using System.Reflection;

namespace ConsoleApplication1
{
   public class Class1
    {
        public static void SayHelloTo([Optional, DefaultParameterValue("world")] string whom)
        {
            Console.WriteLine("Hello " + whom);
        }

       [STAThread]
       public static void Main(string[] args)
       {
            MethodInfo mi = typeof(Class1).GetMethod("sayHelloTo");
            mi.Invoke(null, new Object[] { Missing.Value });
       }
    }
}

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

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

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

另一种选择是使用params关键字

public void DoSomething(params object[] theObjects)
{
  foreach(object o in theObjects)
  {
    // Something with the Objects…
  }
}

叫喜欢……

DoSomething(this, that, theOther);

而不是默认参数,为什么不直接从传入的querystring构造一个字典类..一个几乎与asp.net表单处理查询字符串的方式相同的实现。

即请求。查询字符串(“a”)

这将使叶子类与工厂/样板代码解耦。


您可能还想使用ASP.NET检查Web服务。Web服务是通过c#类的属性自动生成的Web api。