10

如何将可选参数传递给 C# 中的方法?

假设我创建了一个名为 SendCommand 的方法

public void SendCommand(string command,string strfileName)
{
            
    if (command == "NLST *" ) //Listing Files from Server.
    {
        //code
    }
    else if (command == "STOR " + Path.GetFileName(uploadfilename)) //Uploading file to Server
    {
        //code
    }
    else if ...
}

现在我想在 main 方法中调用这个方法,比如

SendCommand("STOR ", filename);
SendCommand("LIST"); // In this case i don't want to pass the second parameter

如何做到这一点?

4

13 回答 13

17

在 .NET 4 之前,您需要重载该方法:

public void sendCommand(String command)
{
    sendCommand(command, null);
}

.NET 4 引入了对默认参数的支持,允许您在一行中完成所有这些操作。

public void SendCommand(String command, string strfilename = null)
{
  //method body as in question
}

顺便说一句,在您编写的问题中,您也没有在第一个示例中调用该方法:

Sendcommand("STOR " + filename);

仍然使用一个参数,它是两个字符串的连接。

于 2010-07-29T08:47:13.897 回答
14

使用 params 属性:

public void SendCommand(String command, params string[] strfilename)
{
}

那么你可以这样称呼它:

SendCommand("cmd");
SendCommand("cmd", "a");
SendCommand("cmd", "b");

或者,如果您使用 C# 4.0,您可以使用新的可选参数功能:

public void SendCommand(String command, string strfilename=null)
{ 
   if (strfilename!=null) .. 
}
于 2010-07-29T08:50:03.630 回答
5

显而易见的答案应该是,不要那样做

您应该为每个命令设置一个单独的方法,或者为每个命令设置一个命令基类和一个单独的派生类,并使用 Execute 方法。

使用一种方法来处理所有可能的命令是糟糕的设计。

您真的不希望一个Sendcommand()人处理所有可能的命令。

于 2010-07-29T08:56:34.753 回答
1

检查C# 4.0 可选参数

还要确保您使用的是 .NET 4。

如果您需要使用旧版本的 .NET。

方法重载是解决方案:

public void SendCommand(String command)
{
    SendCommand(command, null);
    // or SendCommand(command, String.Empty);
} 

public void SendCommand(String command, String fileName)
{
    // your code here
} 
于 2010-07-29T08:52:25.127 回答
1

伙计们,

我在看这个线程,试图解决一个实际上不存在的问题,因为 C#“只是通过”一个 params 数组!直到我尝试过才知道。

这是一个SSCCE:

using System;
using System.Diagnostics; // for Conditional compilation of method CONTENTS

namespace ConsoleApplication3
{
    public static class Log
    {
        [Conditional("DEBUG")] // active in Debug builds only (a no-op in Release builds)
        public static void Debug(string format, params object[] parms) {
            Console.WriteLine(format, parms); 
            // calls Console.WriteLine(string format, params object[] arg);
            // which I presume calls String.Format(string format, params object[] arg);
            // (Sweet! just not what I expected ;-)
        }
    }

    class Program //LogTest
    {
        static void Main(string[] args) {
            Log.Debug("args[0]={0} args[1]={1}", "one", "two");
            Console.Write("Press any key to continue . . .");
            Console.ReadKey();
        }

    }
}

产生:

args[0]=one args[1]=two

甜的!

但为什么?...好吧,因为(当然)与重载的 Console.WriteLine 方法最接近的参数匹配是(string format, params object[] arg)...不是(string format, object arg)我想的那样。

我有点知道这必须以某种方式成为可能,因为(我认为)Console.WriteLine 做到了,我只是以某种方式期望它很难......因此认为这个技巧的简单性和“好” - the-language 值得注意。

CSharpLanguageDesigners.ToList().ForEach(dude=>dude.Kudos++);

干杯。基思。

PS:我想知道 VB.NET 的行为方式是否相同?我想它必须。

于 2012-09-25T23:05:08.370 回答
0

可选参数功能来自 c# 4.0这里是链接。否则你必须编写重载函数。

于 2010-07-29T08:52:25.830 回答
0

此页面上给出的所有答案都是接受可选参数的有效方法,但在许多情况下,这表明您的方法试图做太多事情。

在许多情况下,使用以下明确的方法可能会更好...

public void GetFileListFromServer()
{
    //Listing Files from Server.
    //code
}

public void UploadFileToServer(string strfilename)
{
    //Uploading file to Server
    //code
}
于 2010-07-29T08:56:50.213 回答
0

对此有三种简单的解决方案:

  1. 重载方法
  2. 允许方法接受'null',并适当处理
  3. 使用 .NET 4,它允许可选参数
于 2010-07-29T08:47:23.163 回答
0

创建另一个调用第一个方法的方法?

public void SendCommand(String command)
{
    SendCommand(command, null);
}
于 2010-07-29T08:48:00.387 回答
0

重载函数。而不是检查条件分支。像这样的东西:

public void SendCommand(String command,string strfilename)
{    
    if (command == "STOR " + 
        Path.GetFileName(uploadfilename)) //Uploading file to Server
    {
        //code
    }
    else if ............
}

public void SendCommand(String command)
{ 
        //code

}
于 2010-07-29T08:49:58.200 回答
0

您可以通过几种方式做到这一点。如果您使用的是 .NET 4.0,则可以在方法上使用可选参数:

public void SendCommand(String command,string strfilename = null)
{
    ....
}

否则,您可以创建另一个方法来调用您已有的方法,但传递您希望为可选的默认参数:

public void SendCommand(String command)
{
    SendCommand(command,null);
}
于 2010-07-29T08:50:24.827 回答
0

您可以使用 params 关键字:

private static void SendCommand(String command, params string[] filenames)
{

    if (command == "NLST *" ) //Listing Files from Server.
    {
        //code
    }

    if (command == "STOR ")
    {
        foreach (string fileName in filenames)
        {
            if (String.IsNullOrWhiteSpace(fileName))
            {
                // code
            }
        }
    }
}

您可以将其用作:

static void Main(string[] args)
{
    SendCommand("NLST *");
    SendCommand("STOR ", "myfile1.txt", "myfile.txt");
}
于 2010-07-29T09:10:42.750 回答
0

此处尚未提出使用Runtime.InteropServices[option]命名空间的属性。

检查在 C# 中使方法参数可选的 4 种不同方法

于 2020-12-16T12:15:24.660 回答