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

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

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

其他回答

你也可以试试这个 1型 你的方法(int a=0, int b =0) { / /一些代码 }

2型 你的方法(int?一个,int ?b) { / /一些代码 }

从这个网站:

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”。

可选世界

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

int MyMetod(int param1, int param2, int param3=10, int param4=20){....}

当你调用这个方法时,你可以像这样跳过参数:

int variab = MyMethod(param3:50; param1:10);

c# 4.0实现了一个叫做“命名参数”的特性,你实际上可以通过参数的名字来传递参数,当然你可以按照你想要的任何顺序来传递参数:)

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

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

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


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