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.
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
pu开发者_如何学Goblic 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.
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.
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!
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.
精彩评论