方法在C#4.0超载VS可选参数可选、参数、方法、VS

由网友(倾尽所洧呮为你)分享简介:哪一个更好?一目了然可选参数似乎更好(少code,少XML文档等),但为什么大多数的MSDN库类使用超载而不是可选的参数?which one is better? at a glance optional parameter seems better (less code, less XML documentatio...

哪一个更好?一目了然可选参数似乎更好(少code,少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的是,它presents我们提供了一个优雅的替代方法超载,你根据参数的个数重载方法。

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(1) FOO(1,2) FOO(1,2, 你好)。用方法重载,你会实现这样的解决方案,

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) 

使用命名参数的另一个好处是,它极大地提高了可读性和可选参数的方法因此code维护。

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

请注意是如何的一种方法pretty的多,使多余不必定义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.

阅读全文

相关推荐

最新文章