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

发布于 2024-07-29 19:51:09 字数 212 浏览 2 评论 0原文

我可以设置方法签名,例如

cookEgg(boolean hardBoiled = true)

在其他语言中,如果我在方法调用中没有收到参数,

This defaults the parameter hardboiled to true。 我如何在 C# 中实现这一目标?

In other languages I can set up the method signature like

cookEgg(boolean hardBoiled = true)

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

How would I achieve this in C#?

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

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

发布评论

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

评论(3

挥剑断情 2024-08-05 19:51:09

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

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

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

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.

陪我终i 2024-08-05 19:51:09

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

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

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

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

笑红尘 2024-08-05 19:51:09

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

void test(params int []arg) { }

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

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