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

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

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


当前回答

可选世界

如果希望运行时提供默认参数值,则必须使用反射进行调用。虽然没有这个问题的其他建议那么好,但是与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 });
       }
    }
}

其他回答

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

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

叫喜欢……

DoSomething(this, that, theOther);

可选世界

如果希望运行时提供默认参数值,则必须使用反射进行调用。虽然没有这个问题的其他建议那么好,但是与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 });
       }
    }
}

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

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

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


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

可选参数只是默认参数! 我建议给它们都设置默认参数。 GetFooBar(int a=0, int b=0)如果你没有任何重载方法,将导致a=0,如果你不传递任何值,b=0,如果你传递1个值,将导致,a的传递值为0,如果你传递2个值,第一个将被分配给a,第二个分配给b。

希望这回答了你的问题。

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

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

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