gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:52:32 36 4
gpt4 key购买 nike

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

例如,在 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/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com