如何在c#中使用可选参数?

时间:2022-10-28 10:51:36

Note: This question was asked at a time when C# did not yet support optional parameters (i.e. before C# 4).

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

We're building a web API that's programmatically generated from a C# class. The class has method GetFooBar(int a, int b) and the API has a method GetFooBar taking query params like &a=foo &b=bar.

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

The classes needs to support optional parameters, which isn't supported in C# the language. What's the best approach?

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

18 个解决方案

#1


864  

Surprised no one mentioned C# 4.0 optional parameters that work like this:

令人惊讶的是,没有人提到c# 4.0可选参数:

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

Edit: I know that at the time the question was asked, C# 4.0 didn't exist. But this question still ranks #1 in Google for "C# optional arguments" so I thought - this answer worth being here. Sorry.

编辑:我知道在问题被问到的时候,c# 4.0并不存在。但是这个问题在谷歌中仍然排在第1位,表示“c#可选参数”,所以我认为这个答案值得在这里讨论。对不起。

#2


112  

Another option is to use the params keyword

另一个选项是使用params关键字

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

Called like...

叫喜欢……

DoSomething(this, that, theOther);

#3


68  

In C#, I would normally use multiple forms of the method:

在c#中,我通常会使用多种形式的方法:

void GetFooBar(int a) { int defaultBValue;  GetFooBar(a, defaultBValue); }
void GetFooBar(int a, int b)
{
 // whatever here
}

UPDATE: This mentioned above WAS the way that I did default values with C# 2.0. The projects I'm working on now are using C# 4.0 which now directly supports optional parameters. Here is an example I just used in my own code:

更新:上面提到的是我使用c# 2.0默认值的方式。我现在正在开发的项目使用的是c# 4.0,它现在直接支持可选参数。下面是我在自己的代码中用到的一个例子:

public EDIDocument ApplyEDIEnvelop(EDIVanInfo sender, 
                                   EDIVanInfo receiver, 
                                   EDIDocumentInfo info,
                                   EDIDocumentType type 
                                     = new EDIDocumentType(EDIDocTypes.X12_814),
                                   bool Production = false)
{
   // My code is here
}

#4


39  

From this site:

从这个网站:

http://www.tek-tips.com/viewthread.cfm?qid=1500861&page=1

http://www.tek-tips.com/viewthread.cfm?qid=1500861&page=1

C# does allow the use of the [Optional] attribute (from VB, though not functional in C#). So you can have a method like this:

c#确实允许使用[Optional]属性(来自VB,但在c#中不起作用)。你可以有这样的方法

using System.Runtime.InteropServices;
public void Foo(int a, int b, [Optional] int c)
{
  ...
}

In our API wrapper, we detect optional parameters (ParameterInfo p.IsOptional) and set a default value. The goal is to mark parameters as optional without resorting to kludges like having "optional" in the parameter name.

在我们的API包装器中,我们检测可选参数(ParameterInfo p.IsOptional)并设置一个默认值。目标是将参数标记为可选的,而不必使用诸如在参数名中有“可选”这样的组装。

#5


21  

You could use method overloading...

你可以用方法重载…

GetFooBar()
GetFooBar(int a)
GetFooBar(int a, int b)

It depends on the method signatures, the example I gave is missing the "int b" only method because it would have the same signature as the "int a" method.

它依赖于方法签名,我给出的示例只缺少“int b”方法,因为它与“int a”方法具有相同的签名。

You could use Nullable types...

您可以使用可空类型……

GetFooBar(int? a, int? b)

You could then check, using a.HasValue, to see if a parameter has been set.

你可以用a检查。HasValue,查看是否设置了参数。

Another option would be to use a 'params' parameter.

另一个选择是使用“params”参数。

GetFooBar(params object[] args)

If you wanted to go with named parameters would would need to create a type to handle them, although I think there is already something like this for web apps.

如果您想使用命名参数,则需要创建一个类型来处理它们,尽管我认为web应用程序已经有了类似的东西。

#6


18  

You can use optional parameters in C# 4.0 without any worries. If we have a method like:

您可以在c# 4.0中使用可选参数,而不用担心。如果我们有这样的方法:

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

when you call the method, you can skip parameters like this:

调用该方法时,可以跳过如下参数:

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

C# 4.0 implements a feature called "named parameters", you can actually pass parameters by their names, and of course you can pass parameters in whatever order you want :)

c# 4.0实现了一个名为“命名参数”的特性,您实际上可以通过它们的名称传递参数,当然,您可以按照您想要的顺序传递参数:)

#7


17  

Hello Optional World

If you want the runtime to supply a default parameter value, you have to use reflection to make the call. Not as nice as the other suggestions for this question, but compatible with VB.NET.

如果希望运行时提供默认参数值,则必须使用反射来进行调用。不像其他的建议那么好,但与VB.NET兼容。

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

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

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

#8


8  

An elegant and easy way which allows you to omit any parameters in any position, by taking advantage of nullable types is as follows:

一种优雅而简单的方法,可以利用可空类型在任何位置省略任何参数,如下所示:

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("-");
}

Strings are already nullable types so they don't need the ?.

字符串已经为空类型,所以它们不需要?。

Once you have this method, the following calls are all valid:

一旦你有了这个方法,下面的调用都是有效的:

PrintValues (1, 2, 2.2f);
PrintValues (1, c: 1.2f);
PrintValues(b:100);
PrintValues (c: 1.2f, s: "hello");
PrintValues();

When you define a method that way you have the freedom to set just the parameters you want by naming them. See the following link for more information on named and optional parameters:

当您以这种方式定义一个方法时,您可以*地通过命名参数来设置所需的参数。有关命名参数和可选参数的更多信息,请参见以下链接:

Named and Optional Arguments (C# Programming Guide) @ MSDN

命名和可选参数(c#编程指南)@ MSDN

#9


7  

I agree with stephenbayer. But since it is a webservice, it is easier for end-user to use just one form of the webmethod, than using multiple versions of the same method. I think in this situation Nullable Types are perfect for optional parameters.

我同意stephenbayer。但是由于它是一个webservice,终端用户只使用webmethod的一种形式比使用同一方法的多个版本更容易。我认为在这种情况下,空类型是可选参数的完美选择。

public void Foo(int a, int b, int? c)
{
  if(c.HasValue)
  {
    // do something with a,b and c
  }
  else
  {
    // do something with a and b only
  }  
}

#10


6  

optional parameters are for methods. if you need optional arguments for a class and you are:

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

  • 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:

    使用c# 4.0:在类的构造函数中使用可选参数,这是我比较喜欢的一种解决方案,因为它更接近于使用方法完成的操作,因此更容易记住。这里有一个例子:

    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:

    使用c#4.0之前的c#版本:您应该使用构造函数链接(使用:this关键字),在这里,更简单的构造函数会导致“主构造函数”。例子:

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

#11


2  

The typical way this is handled in C# as stephen mentioned is to overload the method. By creating multiple versions of the method with different parameters you effectively create optional parameters. In the forms with fewer parameters you would typically call the form of the method with all of the parameters setting your default values in the call to that method.

正如stephen提到的,在c#中处理这个问题的典型方法是重载方法。通过创建具有不同参数的方法的多个版本,您可以有效地创建可选参数。在具有较少参数的表单中,您通常会调用方法的形式,所有参数都在调用该方法时设置默认值。

#12


1  

You can overload your method. One method contains one parameter GetFooBar(int a) and the other contain both parameters, GetFooBar(int a, int b)

你可以使你的方法超负荷。一个方法包含一个参数GetFooBar(int a),另一个方法包含两个参数GetFooBar(int a, int b)

#13


0  

Instead of default parameters, why not just construct a dictionary class from the querystring passed .. an implementation that is almost identical to the way asp.net forms work with querystrings.

与其使用默认参数,不如从传递的querystring构造一个dictionary类。一种实现,与asp.net窗体与querystring的工作方式几乎相同。

i.e. Request.QueryString["a"]

例如Request.QueryString[a]

This will decouple the leaf class from the factory / boilerplate code.

这将使leaf类与工厂/样板代码分离。


You also might want to check out Web Services with ASP.NET. Web services are a web api generated automatically via attributes on C# classes.

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

#14


0  

A little late to the party, but I was looking for the answer to this question and ultimately figured out yet another way to do this. Declare the data types for the optional args of your web method to be type XmlNode. If the optional arg is omitted this will be set to null, and if it's present you can get is string value by calling arg.Value, i.e.,

派对有点晚了,但我一直在寻找这个问题的答案,最终找到了另一种解决办法。将web方法的可选args的数据类型声明为XmlNode类型。如果省略了可选的arg,则将其设置为null,如果存在,则可以通过调用arg获得is字符串值。值,即

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

What's also decent about this approach is the .NET generated home page for the ws still shows the argument list (though you do lose the handy text entry boxes for testing).

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

#15


0  

I have a web service to write that takes 7 parameters. Each is an optional query attribute to a sql statement wrapped by this web service. So two workarounds to non-optional params come to mind... both pretty poor:

我要编写一个web服务,它包含7个参数。每个都是由这个web服务包装的sql语句的可选查询属性。所以我想到了两个解决非可选参数的方法……都很差:

method1(param1, param2, param 3, param 4, param 5, param 6, param7) method1(param1, param2, param3, param 4, param5, param 6) method 1(param1, param2, param3, param4, param5, param7)... start to see the picture. This way lies madness. Way too many combinations.

方法1(param1, param2, param3, param4, param5, param 6, param5, param 6)方法1(param1, param2, param3, param4, param5, param 6)方法1(param1, param2, param3, param4, param5, param7)。开始看图片。这种方式是疯狂。太多的组合。

Now for a simpler way that looks awkward but should work: method1(param1, bool useParam1, param2, bool useParam2, etc...)

现在让我们来看一种更简单的方法:method1(param1、bool useParam1、param2、bool useParam2,等等)

That's one method call, values for all parameters are required, and it will handle each case inside it. It's also clear how to use it from the interface.

这是一个方法调用,所有参数的值都是必需的,它会处理其中的每个情况。从接口使用它也很清楚。

It's a hack, but it will work.

这是一种技巧,但它会起作用。

#16


0  

I had to do this in a VB.Net 2.0 Web Service. I ended up specifying the parameters as strings, then converting them to whatever I needed. An optional parameter was specified with an empty string. Not the cleanest solution, but it worked. Just be careful that you catch all the exceptions that can occur.

我必须用VB。Net 2.0 Web服务。最后我将参数指定为字符串,然后将它们转换为我需要的任何参数。用空字符串指定可选参数。这不是最干净的解决方案,但它奏效了。只是要注意捕捉可能发生的所有异常。

#17


0  

For just in case if someone wants to pass a callback (or delegate) as an optional parameter, can do it this way.

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

Optional Callback parameter:

可选的回调参数:

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

#18


-2  

You can try this too
Type 1
public void YourMethod(int a=0, int b = 0) { //some code }

你也可以试试这个类型1 public void你的方法(int a=0, int b =0) {// /some code}


Type 2
public void YourMethod(int? a, int? b) { //some code }

类型2 public void YourMethod(int?一个,int ?b){//一些代码}

#1


864  

Surprised no one mentioned C# 4.0 optional parameters that work like this:

令人惊讶的是,没有人提到c# 4.0可选参数:

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

Edit: I know that at the time the question was asked, C# 4.0 didn't exist. But this question still ranks #1 in Google for "C# optional arguments" so I thought - this answer worth being here. Sorry.

编辑:我知道在问题被问到的时候,c# 4.0并不存在。但是这个问题在谷歌中仍然排在第1位,表示“c#可选参数”,所以我认为这个答案值得在这里讨论。对不起。

#2


112  

Another option is to use the params keyword

另一个选项是使用params关键字

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

Called like...

叫喜欢……

DoSomething(this, that, theOther);

#3


68  

In C#, I would normally use multiple forms of the method:

在c#中,我通常会使用多种形式的方法:

void GetFooBar(int a) { int defaultBValue;  GetFooBar(a, defaultBValue); }
void GetFooBar(int a, int b)
{
 // whatever here
}

UPDATE: This mentioned above WAS the way that I did default values with C# 2.0. The projects I'm working on now are using C# 4.0 which now directly supports optional parameters. Here is an example I just used in my own code:

更新:上面提到的是我使用c# 2.0默认值的方式。我现在正在开发的项目使用的是c# 4.0,它现在直接支持可选参数。下面是我在自己的代码中用到的一个例子:

public EDIDocument ApplyEDIEnvelop(EDIVanInfo sender, 
                                   EDIVanInfo receiver, 
                                   EDIDocumentInfo info,
                                   EDIDocumentType type 
                                     = new EDIDocumentType(EDIDocTypes.X12_814),
                                   bool Production = false)
{
   // My code is here
}

#4


39  

From this site:

从这个网站:

http://www.tek-tips.com/viewthread.cfm?qid=1500861&page=1

http://www.tek-tips.com/viewthread.cfm?qid=1500861&page=1

C# does allow the use of the [Optional] attribute (from VB, though not functional in C#). So you can have a method like this:

c#确实允许使用[Optional]属性(来自VB,但在c#中不起作用)。你可以有这样的方法

using System.Runtime.InteropServices;
public void Foo(int a, int b, [Optional] int c)
{
  ...
}

In our API wrapper, we detect optional parameters (ParameterInfo p.IsOptional) and set a default value. The goal is to mark parameters as optional without resorting to kludges like having "optional" in the parameter name.

在我们的API包装器中,我们检测可选参数(ParameterInfo p.IsOptional)并设置一个默认值。目标是将参数标记为可选的,而不必使用诸如在参数名中有“可选”这样的组装。

#5


21  

You could use method overloading...

你可以用方法重载…

GetFooBar()
GetFooBar(int a)
GetFooBar(int a, int b)

It depends on the method signatures, the example I gave is missing the "int b" only method because it would have the same signature as the "int a" method.

它依赖于方法签名,我给出的示例只缺少“int b”方法,因为它与“int a”方法具有相同的签名。

You could use Nullable types...

您可以使用可空类型……

GetFooBar(int? a, int? b)

You could then check, using a.HasValue, to see if a parameter has been set.

你可以用a检查。HasValue,查看是否设置了参数。

Another option would be to use a 'params' parameter.

另一个选择是使用“params”参数。

GetFooBar(params object[] args)

If you wanted to go with named parameters would would need to create a type to handle them, although I think there is already something like this for web apps.

如果您想使用命名参数,则需要创建一个类型来处理它们,尽管我认为web应用程序已经有了类似的东西。

#6


18  

You can use optional parameters in C# 4.0 without any worries. If we have a method like:

您可以在c# 4.0中使用可选参数,而不用担心。如果我们有这样的方法:

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

when you call the method, you can skip parameters like this:

调用该方法时,可以跳过如下参数:

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

C# 4.0 implements a feature called "named parameters", you can actually pass parameters by their names, and of course you can pass parameters in whatever order you want :)

c# 4.0实现了一个名为“命名参数”的特性,您实际上可以通过它们的名称传递参数,当然,您可以按照您想要的顺序传递参数:)

#7


17  

Hello Optional World

If you want the runtime to supply a default parameter value, you have to use reflection to make the call. Not as nice as the other suggestions for this question, but compatible with VB.NET.

如果希望运行时提供默认参数值,则必须使用反射来进行调用。不像其他的建议那么好,但与VB.NET兼容。

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

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

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

#8


8  

An elegant and easy way which allows you to omit any parameters in any position, by taking advantage of nullable types is as follows:

一种优雅而简单的方法,可以利用可空类型在任何位置省略任何参数,如下所示:

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("-");
}

Strings are already nullable types so they don't need the ?.

字符串已经为空类型,所以它们不需要?。

Once you have this method, the following calls are all valid:

一旦你有了这个方法,下面的调用都是有效的:

PrintValues (1, 2, 2.2f);
PrintValues (1, c: 1.2f);
PrintValues(b:100);
PrintValues (c: 1.2f, s: "hello");
PrintValues();

When you define a method that way you have the freedom to set just the parameters you want by naming them. See the following link for more information on named and optional parameters:

当您以这种方式定义一个方法时,您可以*地通过命名参数来设置所需的参数。有关命名参数和可选参数的更多信息,请参见以下链接:

Named and Optional Arguments (C# Programming Guide) @ MSDN

命名和可选参数(c#编程指南)@ MSDN

#9


7  

I agree with stephenbayer. But since it is a webservice, it is easier for end-user to use just one form of the webmethod, than using multiple versions of the same method. I think in this situation Nullable Types are perfect for optional parameters.

我同意stephenbayer。但是由于它是一个webservice,终端用户只使用webmethod的一种形式比使用同一方法的多个版本更容易。我认为在这种情况下,空类型是可选参数的完美选择。

public void Foo(int a, int b, int? c)
{
  if(c.HasValue)
  {
    // do something with a,b and c
  }
  else
  {
    // do something with a and b only
  }  
}

#10


6  

optional parameters are for methods. if you need optional arguments for a class and you are:

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

  • 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:

    使用c# 4.0:在类的构造函数中使用可选参数,这是我比较喜欢的一种解决方案,因为它更接近于使用方法完成的操作,因此更容易记住。这里有一个例子:

    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:

    使用c#4.0之前的c#版本:您应该使用构造函数链接(使用:this关键字),在这里,更简单的构造函数会导致“主构造函数”。例子:

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

#11


2  

The typical way this is handled in C# as stephen mentioned is to overload the method. By creating multiple versions of the method with different parameters you effectively create optional parameters. In the forms with fewer parameters you would typically call the form of the method with all of the parameters setting your default values in the call to that method.

正如stephen提到的,在c#中处理这个问题的典型方法是重载方法。通过创建具有不同参数的方法的多个版本,您可以有效地创建可选参数。在具有较少参数的表单中,您通常会调用方法的形式,所有参数都在调用该方法时设置默认值。

#12


1  

You can overload your method. One method contains one parameter GetFooBar(int a) and the other contain both parameters, GetFooBar(int a, int b)

你可以使你的方法超负荷。一个方法包含一个参数GetFooBar(int a),另一个方法包含两个参数GetFooBar(int a, int b)

#13


0  

Instead of default parameters, why not just construct a dictionary class from the querystring passed .. an implementation that is almost identical to the way asp.net forms work with querystrings.

与其使用默认参数,不如从传递的querystring构造一个dictionary类。一种实现,与asp.net窗体与querystring的工作方式几乎相同。

i.e. Request.QueryString["a"]

例如Request.QueryString[a]

This will decouple the leaf class from the factory / boilerplate code.

这将使leaf类与工厂/样板代码分离。


You also might want to check out Web Services with ASP.NET. Web services are a web api generated automatically via attributes on C# classes.

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

#14


0  

A little late to the party, but I was looking for the answer to this question and ultimately figured out yet another way to do this. Declare the data types for the optional args of your web method to be type XmlNode. If the optional arg is omitted this will be set to null, and if it's present you can get is string value by calling arg.Value, i.e.,

派对有点晚了,但我一直在寻找这个问题的答案,最终找到了另一种解决办法。将web方法的可选args的数据类型声明为XmlNode类型。如果省略了可选的arg,则将其设置为null,如果存在,则可以通过调用arg获得is字符串值。值,即

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

What's also decent about this approach is the .NET generated home page for the ws still shows the argument list (though you do lose the handy text entry boxes for testing).

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

#15


0  

I have a web service to write that takes 7 parameters. Each is an optional query attribute to a sql statement wrapped by this web service. So two workarounds to non-optional params come to mind... both pretty poor:

我要编写一个web服务,它包含7个参数。每个都是由这个web服务包装的sql语句的可选查询属性。所以我想到了两个解决非可选参数的方法……都很差:

method1(param1, param2, param 3, param 4, param 5, param 6, param7) method1(param1, param2, param3, param 4, param5, param 6) method 1(param1, param2, param3, param4, param5, param7)... start to see the picture. This way lies madness. Way too many combinations.

方法1(param1, param2, param3, param4, param5, param 6, param5, param 6)方法1(param1, param2, param3, param4, param5, param 6)方法1(param1, param2, param3, param4, param5, param7)。开始看图片。这种方式是疯狂。太多的组合。

Now for a simpler way that looks awkward but should work: method1(param1, bool useParam1, param2, bool useParam2, etc...)

现在让我们来看一种更简单的方法:method1(param1、bool useParam1、param2、bool useParam2,等等)

That's one method call, values for all parameters are required, and it will handle each case inside it. It's also clear how to use it from the interface.

这是一个方法调用,所有参数的值都是必需的,它会处理其中的每个情况。从接口使用它也很清楚。

It's a hack, but it will work.

这是一种技巧,但它会起作用。

#16


0  

I had to do this in a VB.Net 2.0 Web Service. I ended up specifying the parameters as strings, then converting them to whatever I needed. An optional parameter was specified with an empty string. Not the cleanest solution, but it worked. Just be careful that you catch all the exceptions that can occur.

我必须用VB。Net 2.0 Web服务。最后我将参数指定为字符串,然后将它们转换为我需要的任何参数。用空字符串指定可选参数。这不是最干净的解决方案,但它奏效了。只是要注意捕捉可能发生的所有异常。

#17


0  

For just in case if someone wants to pass a callback (or delegate) as an optional parameter, can do it this way.

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

Optional Callback parameter:

可选的回调参数:

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

#18


-2  

You can try this too
Type 1
public void YourMethod(int a=0, int b = 0) { //some code }

你也可以试试这个类型1 public void你的方法(int a=0, int b =0) {// /some code}


Type 2
public void YourMethod(int? a, int? b) { //some code }

类型2 public void YourMethod(int?一个,int ?b){//一些代码}