.net 如何将可选参数传递给 C# 中的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3360727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass optional parameters to a method in C#?
提问by Swapnil Gupta
How to pass optional parameters to a method in C# ?
如何将可选参数传递给 C# 中的方法?
Suppose i created one method called Sendcommand
假设我创建了一个名为 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 dont want to pass the second parameter
How to achieve that?
如何做到这一点?
回答by Martin Harris
Pre .NET 4 you need to overload the method:
在 .NET 4 之前,您需要重载该方法:
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.
.NET 4 引入了对默认参数的支持,允许您在一行中完成所有这些。
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.
仍然使用单个参数,即两个字符串的串联。
回答by codymanix
Use the params attribute:
使用 params 属性:
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:
或者,如果您使用 C# 4.0,您可以使用新的可选参数功能:
public void SendCommand(String command, string strfilename=null)
{
if (strfilename!=null) ..
}
回答by Kieren Johnstone
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.
您应该为每个命令拥有一个单独的方法,或者为每个命令拥有一个命令基类和一个单独的派生类,以及一个 Execute 方法。
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.
你真的不希望一个Sendcommand()人处理每一个可能的命令。
回答by corlettk
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.
我正在查看这个线程,试图解决一个实际上并不存在的问题,因为 C#“只是通过”了一个 params 数组!直到我试过才知道。
Here's an SSCCE:
这是一个 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.
但为什么?...嗯,因为(当然)与重载的 Console.WriteLine 方法最接近的参数匹配是(string format, params object[] arg)... 不像(string format, object arg)我想的那样。
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.
我有点知道这必须以某种方式成为可能,因为(我认为)Console.WriteLine 做到了,我只是以某种方式期望它很难......因此认为这个技巧的简单性和“好” -语言是值得注意的。
CSharpLanguageDesigners.ToList().ForEach(dude=>dude.Kudos++);
Cheers. Keith.
干杯。基思。
PS:I wonder if VB.NET behaves the same way? I suppose it must.
PS:我想知道 VB.NET 的行为是否相同?我想它必须。
回答by Incognito
Check C# 4.0 Optional Parameters.
检查C# 4.0 可选参数。
Also make sure you are using .NET 4.
还要确保您使用的是 .NET 4。
If you need to use older versions of .NET.
如果您需要使用旧版本的 .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
}
回答by Siddiqui
回答by Jonathon Bolster
You can do this in a few ways. If you're using .NET 4.0, you can use optional parameters on the method:
您可以通过几种方式做到这一点。如果您使用 .NET 4.0,您可以在方法上使用可选参数:
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);
}
回答by Flynn1179
There's three easy solutions to this one:
对此有三种简单的解决方案:
- Overload the method
- Allow the method to accept 'null', and handle appropriately
- Use .NET 4, which allows optional parameters
- 重载方法
- 允许方法接受“null”,并适当处理
- 使用 .NET 4,它允许可选参数
回答by Arcturus
Create another method which calls the first?
创建另一个调用第一个方法的方法?
public void SendCommand(String command)
{
SendCommand(command, null);
}
回答by loxxy
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
}

