方法重载与可选参数
我似乎记得读过 C# 4.0 中的方法重载(和构造函数链接)和可选参数之间存在重要差异,但我无法找到任何承认任何差异的内容。
以下两个实现之间有什么重要区别吗?
第一
public void Foo()
{
Foo(String.Empty);
}
public void Foo(string message)
{
Console.WriteLine(message);
}
第二
public void Foo(string message = "")
{
Console.WriteLine(message);
}
I seem to recall reading there was an important difference between method overloading (and constructor chaining) and optional parameters in C# 4.0, but I haven't been able to locate anything acknowledging any difference.
Are there any important differences between the following two implementations?
First
public void Foo()
{
Foo(String.Empty);
}
public void Foo(string message)
{
Console.WriteLine(message);
}
Second
public void Foo(string message = "")
{
Console.WriteLine(message);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
可选参数是语法糖。
除了与以前版本的 .NET 向后兼容之外,它们是相同的。
Optional parameters is syntactic sugar.
Other than backwards compatibility with previous versions of .NET they are the same.
我赞成方法重载。可选参数存在已知版本控制问题参数。
Jon Skeet 写了一篇非常好的文章 这里。
添加此功能的动机是使与 COM 的通信更加容易,其中方法可以有很多参数,而对于 C# 类的新设计实践来说则更少
I would favour method overloading. There are known versioning issues with optional parameters.
There is a very good article by Jon Skeet here.
Motivation for adding this was making it easier to talk to COM where methods can have many many parameters and less fora new design practice for C# classes
可选参数的作用类似于常量,并在编译时被替换。
将为调用者生成代码:
这意味着如果您选择在新版本中更改默认值,则引用您的程序集的所有程序集都将具有旧的默认值!
重载不像常量,并且隐藏程序集中的默认值。这提供了一条干净的升级路径。
Optional parameters act like constants, and are replaced at compile-time.
Will generate the code for the caller:
This means all the assemblies referencing yours will have the OLD default if you choose to change the default in a new version!
Overloads don't act like constants, and hide the defaults in your assembly. This gives a clean upgrade path.
我会选择第二个选项。您可以将默认字符串更改为某个常量,然后稍后您可以更改该常量的值,例如:
另外,您还需要维护一个少(尽管很简单)的函数。
I would go with the second option. You could change the default string to some constant, and then at a later date you can change the value of the constant, such as :
Also, you have one less (albeit simple) function to maintain.