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

发布于 2024-09-11 13:17:24 字数 560 浏览 5 评论 0原文

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

如何实现?

How to pass optional parameters to a method in C#?

Suppose I created one method called 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 ...
}

Now I want to call this method in main method like

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

How to achieve that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

青朷 2024-09-18 13:17:24

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

Use the params attribute:

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

then you can call it like this:

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

or if you use C# 4.0 you can use the new optional arguments feature:

public void SendCommand(String command, string strfilename=null)
{ 
   if (strfilename!=null) .. 
}
李不 2024-09-18 13:17:24

在 .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);

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

Pre .NET 4 you need to overload the method:

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

.NET 4 introduces support for default parameters, which allow you to do all this in one line.

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

By the way, in the question as you have written it you aren't calling the method in your first example either:

Sendcommand("STOR " + filename);

is still using a single parameter which is the concatenation of the two strings.

阳光的暖冬 2024-09-18 13:17:24

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

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

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

您确实不希望一个 Sendcommand() 来处理每个可能的命令。

The obvious answer for this should be, don't do it that way.

You should either have a separate method for each command, or a command base class and a separate derived class for each command, with an Execute method.

It's bad design to have one method that handles every conceivable command.

You really don't want one Sendcommand() to handle every possible command.

以酷 2024-09-18 13:17:24

各位,

我正在查看这个线程,试图解决一个实际上不存在的问题,因为 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正如我所想的那样。

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

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

干杯。基思.

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

Folks,

I was looking at this thread, trying to solve a problem that doesn't actually exist, because C# "just passes through" a params array! Which I didn't know until I just tried it.

Here's an 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();
        }

    }
}

Produces:

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

Sweet!

But why? ... Well because (of course) the closest parameter-match to the heavily-overloaded Console.WriteLine method is (string format, params object[] arg) ... not (string format, object arg) as I was thinking.

I sort-of knew this had to be possible somehow, because (I presume) Console.WriteLine does it, I just somehow expected it to be HARD... and therefore think that the simplicity and "niceness" of this trick-of-the-language is note worthy.

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

Cheers. Keith.

PS: I wonder if VB.NET behaves the same way? I suppose it must.

安穩 2024-09-18 13:17:24

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

Check C# 4.0 Optional Parameters.

Also make sure you are using .NET 4.

If you need to use older versions of .NET.

Method overloading is the solution :

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

public void SendCommand(String command, String fileName)
{
    // your code here
} 
假装不在乎 2024-09-18 13:17:24

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

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

There's three easy solutions to this one:

  1. Overload the method
  2. Allow the method to accept 'null', and handle appropriately
  3. Use .NET 4, which allows optional parameters
━╋う一瞬間旳綻放 2024-09-18 13:17:24

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

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

Create another method which calls the first?

public void SendCommand(String command)
{
    SendCommand(command, null);
}
泛泛之交 2024-09-18 13:17:24

使函数超载。而不是检查条件分支。像这样的事情:

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

}

Overload the function. rather than checking for conditional branch. Something like this:

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

}
婴鹅 2024-09-18 13:17:24

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

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

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

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

You can do this in a few ways. If you're using .NET 4.0, you can use optional parameters on the method:

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

Otherwise, you can just create another method which calls the method you already have but passing the default parameters you want to be optional:

public void SendCommand(String command)
{
    SendCommand(command,null);
}
扎心 2024-09-18 13:17:24

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

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

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

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

All of the answers given on this page are valid ways of accepting optional parameters, but in many cases, this is a sign that your method is trying to do too much.

In many cases you may be better off with the following unambiguous methods...

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

public void UploadFileToServer(string strfilename)
{
    //Uploading file to Server
    //code
}
流心雨 2024-09-18 13:17:24

您可以使用 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");
}

You can use params keyword :

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

and you can use it as :

static void Main(string[] args)
{
    SendCommand("NLST *");
    SendCommand("STOR ", "myfile1.txt", "myfile.txt");
}
愁杀 2024-09-18 13:17:24

这里尚未提议使用 Runtime.InteropServices 命名空间的 [option] 属性。

检查4种不同的方法来制作方法C# 中的参数可选

Using [option] attribute of Runtime.InteropServices namespace has not yet been proposed here.

Check 4 Different ways to make Method Parameter Optional in C#

不疑不惑不回忆 2024-09-18 13:17:24

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

Optional parameters feature come in c# 4.0 here is the link. Otherwise you have to write overloaded function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文