重载是在C#中具有默认函数参数的唯一方法吗?
确实,处理默认函数参数的唯一方法是通过函数重载吗?
例如,在PHP中,我可以这样做:
function foo($x, $y=0) { }
在Cbe中处理它的最好方法是吗?
void foo(int x) { foo(x, 0); } void foo(int x, int y) { }
从这里举起的例子
编辑
使Cexample成为实际的C语言(感谢Blair Conrad)
解决方案
回答
是的,那是最好的选择,除非我们像其他人指出的那样在参数名称上省略$。如果我们对缺少默认参数值的基本原理感兴趣,请参阅@Giovanni Galbo的说明。
回答
默认参数是C ++的一部分,但是从C3.5开始,默认参数仍然不受支持-我们必须重载。从1.0开始,它们已经在VB.Net中可用。
回答
是的。
或者骂。
或者抽象到一个类中并在其中使用默认值。
回答
否,AFAIK C不支持覆盖,是的,这是实现相同效果的推荐方法。
回答
只是为了满足一些好奇心:
从为什么C不支持默认参数?:
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.
回答
关于cfaq的摘录:
那里列出的大多数问题都是为VB.Net解决的(特别是intellisense和xml注释问题),这意味着它们确实是红鲱鱼-Cteam有可用的代码可以解决问题。
另一个原因与强制类的用户重新编译有关,但这也有点让人头疼。如果我们在框架类中更改默认值,而用户不必重新编译,则可能会冒着用户不知道默认值已更改的风险。现在,代码中存在一个潜在的错误,直到运行时才会出现。换句话说,重载该功能的替代方案至少同样糟糕。当然,这也假定该功能的特定实现,但这是常见问题中建议的实现。
因此,我们必须权衡剩下的原因("试图限制魔术")与写重载"不太方便"这一事实(他们承认)。就我个人而言,我说的是放入该功能,然后让程序员决定是否使用它。
回答
这不做这份工作吗?
void foo(int x):this(x, 0){} void foo(int x, int y){ // code here }
回答
正如所指出的那样,这在Chowever中尚不可用,但正如Sam Ng在其博客中讨论的那样,它们将在C4.0中出现。
http://blogs.msdn.com/samng/archive/2009/02/03/named-arguments-optional-arguments-and-default-values.aspx