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

问题描述 投票:0回答:13

如何将可选参数传递给 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 ...
}

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

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

如何实现?

.net c#-4.0 optional-parameters
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);

仍然使用单个参数,即两个字符串的串联。


15
投票

使用 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) .. 
}

5
投票

对此的明显答案应该是,不要那样做

您应该为每个命令提供一个单独的方法,或者为每个命令提供一个命令基类和一个单独的派生类,并具有 Execute 方法。

用一种方法来处理每一个可以想象的命令是糟糕的设计。

您真的不希望一个

Sendcommand()
处理每一个可能的命令。


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 做到了,我只是以某种方式期望它很难......因此认为这个技巧的简单性和“美好” -语言值得注意。

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

干杯。基思。

PS: 我想知道 VB.NET 是否也有同样的行为?我想一定是这样的。


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
} 

0
投票

这个问题有三种简单的解决方案:

  1. 重载方法
  2. 允许方法接受“null”,并进行适当处理
  3. 使用.NET 4,它允许可选参数

0
投票

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

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

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

}

0
投票

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

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

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

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

0
投票

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

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

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

public void UploadFileToServer(string strfilename)
{
    //Uploading file to Server
    //code
}

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

0
投票

此处尚未提出使用

Runtime.InteropServices
命名空间的 [option] 属性。

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


0
投票

c# 4.0 中提供了可选参数功能here 是链接。否则你必须编写重载函数。

© www.soinside.com 2019 - 2024. All rights reserved.