如何在C#中使用默认参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1204437/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:50:52  来源:igfitidea点击:

How to use default parameters in C#?

c#.netparametersdefault-valueoptional-parameters

提问by Chin

In other languages I can set up the method signature like

在其他语言中,我可以设置方法签名,如

cookEgg(boolean hardBoiled = true)

This defaults the parameter hardboiledto true, if I don't receive a parameter in the method call.

如果我在方法调用中没有收到参数,则默认参数hardboiledtrue

How would I achieve this in C#?

我将如何在 C# 中实现这一目标?

采纳答案by Pavel Minaev

At present, you have to overload the method:

目前,您必须重载该方法:

void cookEgg(bool hardBoiled) { ... }
void cookEgg() { cookEgg(true); }

C# 4.0 will add optional arguments - you will be able to write code exactly as in your original sample, and it will work as you'd expect.

C# 4.0 将添加可选参数 - 您将能够完全按照原始示例编写代码,并且它会按您的预期工作。

回答by adatapost

This is not what you look exactly but I think paramsargument is another answer.

这不是你看起来的样子,但我认为params参数是另一个答案。

void test(params int []arg) { }

回答by QrystaL

Default parameters are supported in C# 4 (Visual Studio 2010).

C# 4 (Visual Studio 2010) 支持默认参数。

http://msdn.microsoft.com/en-us/library/dd264739(VS.100).aspx

http://msdn.microsoft.com/en-us/library/dd264739(VS.100).aspx