C# 4.0 中的方法重载与可选参数 [英] method overloading vs optional parameter in C# 4.0

查看:17
本文介绍了C# 4.0 中的方法重载与可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪个更好?乍一看可选参数似乎更好(更少的代码、更少的 XML 文档等),但为什么大多数 MSDN 库类使用重载而不是可选参数?

which one is better? at a glance optional parameter seems better (less code, less XML documentation, etc), but why do most MSDN library classes use overloading instead of optional parameters?

在选择使用可选参数(或重载)时,有什么特别需要注意的地方吗?

Is there any special thing you have to take note when you choose to use optional parameter (or overloading)?

推荐答案

在 C# 4.0 中将可选参数"与命名参数"结合使用的一个很好的用例是,它为我们提供了一种优雅的方法重载替代方案基于参数个数的重载方法.

One good use case for 'Optional parameters' in conjunction with 'Named Parameters' in C# 4.0 is that it presents us with an elegant alternative to method overloading where you overload method based on the number of parameters.

例如说你想要一个方法 foo 像这样被调用/使用,foo()foo(1)foo(1,2), foo(1,2, "hello").通过方法重载,您将实现这样的解决方案,

For example say you want a method foo to be be called/used like so, foo(), foo(1), foo(1,2), foo(1,2, "hello"). With method overloading you would implement the solution like this,

///Base foo method
public void DoFoo(int a, long b, string c)
{
   //Do something
}  

/// Foo with 2 params only
public void DoFoo(int a, long b)
{
    /// ....
    DoFoo(a, b, "Hello");
}

public void DoFoo(int a)
{
    ///....
    DoFoo(a, 23, "Hello");
}

.....

使用 C# 4.0 中的可选参数,您将实现如下用例,

With optional parameters in C# 4.0 you would implement the use case like the following,

public void DoFoo(int a = 10, long b = 23, string c = "Hello")

然后你可以使用这样的方法 - 注意命名参数的使用 -

Then you could use the method like so - Note the use of named parameter -

DoFoo(c:"Hello There, John Doe")

此调用将参数 a 的值为 10,参数 b 的值为 23.此调用的另一个变体 - 请注意,您不需要按照方法签名中出现的顺序设置参数值,命名参数使值显式.

This call takes parameter a value as 10 and parameter b as 23. Another variant of this call - notice you don't need to set the parameter values in the order as they appear in the method signature, the named parameter makes the value explicit.

DoFoo(c:"hello again", a:100) 

使用命名参数的另一个好处是它大大增强了可读性,从而大大增强了可选参数方法的代码维护.

Another benefit of using named parameter is that it greatly enhances readability and thus code maintenance of optional parameter methods.

注意一个方法是如何使在方法重载中定义 3 个或更多方法变得多余的.我发现这是将可选参数与命名参数结合使用的一个很好的用例.

Note how one method pretty much makes redundant having to define 3 or more methods in method overloading. This I have found is a good use case for using optional parameter in conjunction with named parameters.

这篇关于C# 4.0 中的方法重载与可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆