c# - 重载是在 C# 中拥有默认函数参数的唯一方法吗?

标签 c# overloading

处理默认函数参数的唯一方法是通过函数重载,这是真的吗?

例如,在 PHP 中我可以这样做:

function foo($x, $y=0)
{
}

在 C# 中处理它的最佳方法是这样吗?

void foo(int x)
{
  foo(x, 0);
}

void foo(int x, int y)
{
}

Example lifted from here

编辑

将 C# 示例变为实际的 C#(感谢 Blair Conrad)

最佳答案

只是为了满足一些好奇心:

来自 Why doesn't C# support default parameters? :

In languages such as C++, a default value can be included as part of the method declaration:

void Process(Employee employee, bool bonus = false)

This method can be called either with:

a.Process(employee, true);

or

a.Process(employee);

in the second case, the parameter bonus is set to false.

C# doesn't have this feature.

One reason we don't have this feature is related to a specific implementation of the feature. In the C++ world, when the user writes:

a.Process(employee);

the compiler generates

a.process(employee, false);

In other words, the compiler takes the default value that is specified in the method prototype and puts it into the method call - it's just as if the user wrote 'false' as the second parameter. There's no way to change that default value without forcing the user of the class to recompile, which is unfortunate.

The overloading model works better in this respect. The framework author just defines two separate methods, and the single-parameter one calls the two-parameter method. This keeps the default value in the framework, where it can be modified if necessary.

It would be possible for a compiler to take something like the C++ definition and produce the overloads, but there are a few issues with that approach.

The first one is that the correlation between the code that the user writes and the code the compiler generates is less obvious. We generally try to limit magic when possible, as it makes it harder for programmers. The second issue has to do with things like XML doc comments and intellisense. The compiler would have to have special rules for how it generates doc comments for the overloaded methods, and intellisense would need to have smarts to collapse the overloaded methods into a single method.

Writing overloads yourself is a bit less convenient, but we think it's an acceptable solution.

关于c# - 重载是在 C# 中拥有默认函数参数的唯一方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40090/

相关文章:

c# - 在 Asp.Net MVC 3 中通过文化和 UI 文化解决字段本地化问题

c# - 难以使用 WCF 上传大文件

c++ - 指针与 const 和重载的交互

java - 该方法对于错误类型不明确

c++ - 为什么对重载函数的调用不明确?

Java 7 使用可变参数重载

c# - 如何使用 WriteEvent 将事件记录为 Critical

c# - 如何获取 Channel<T> 中的元素数量?

c# - 调用计时器线程返回时线程不会停止

c# - C#编译器正在尝试编译为错误的重载方法