简体   繁体   English

方法重载与可选参数

[英]Method Overloading Versus Optional Parameters

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. 我似乎还记得阅读过C#4.0中的方法重载(和构造函数链接)与可选参数之间的重要区别,但是我无法找到任何承认任何区别的东西。

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);
}

I would favour method overloading. 我更喜欢方法重载。 There are known versioning issues with optional parameters. 可选参数存在已知的版本控制问题。

There is a very good article by Jon Skeet here . 乔恩•斯基特Jon Skeet) 在这里有一篇很好的文章。

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 这样做的动机是使与COM的通信变得更加容易,在COM中方法可以具有很多参数,而对于C#类的新设计实践却更少

Optional parameters act like constants, and are replaced at compile-time. 可选参数的作用类似于常量,并在编译时替换。

public void Foo(string s = "default")
Foo();

Will generate the code for the caller: 将为调用者生成代码:

public void Foo(string s)
Foo("default");

This means all the assemblies referencing yours will have the OLD default if you choose to change the default in a new version! 这意味着,如果您选择在新版本中更改默认值,则引用您的所有程序集都将具有OLD默认值!

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 : 您可以将默认字符串更改为某个常量,然后在以后的某个日期可以更改该常量的值,例如:

constant String defaultString = String.Empty; //change this later if the default value needs to be something else, can't remember if the syntax is valid C# ;)
//...
public void Foo(string message = defaultString)
{
   Console.WriteLine(message);
}

Also, you have one less (albeit simple) function to maintain. 此外,您还需要维护一个少(尽管很简单)的函数。

Optional parameters is syntactic sugar. 可选参数是语法糖。

Other than backwards compatibility with previous versions of .NET they are the same. 除了与.NET的早期版本向后兼容之外,它们是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM