2 .net c# coding-style named-parameters
所以,假设你有:
public void TestFishsticks()
{
var fishes = GetFishstick(false);
}
private object GetFishstick(bool getBigFishes)
{
return FishsticksManager().GetFishsticks(getBigFishes);
}
Run Code Online (Sandbox Code Playgroud)
VS
public void TestFishsticks()
{
var fishes = GetFishstick(getBigFishes: false);
}
private object GetFishstick(bool getBigFishes)
{
return FishsticksManager().GetFishsticks(getBigFishes);
}
Run Code Online (Sandbox Code Playgroud)
这有什么理由吗?
在我目前的公司代码库中,我们似乎都做了两个,但似乎没有理由一个在另一个.我可以通过第二种选择看到一个小的可读性改进,因为你可以立即看到参数名称,但你还可以通过intellisense看到它?
命名参数主要在C#4.0中引入,以提高可读性.你实际上不必使用它们.有些人喜欢在某些情况下使用它们,有些则不喜欢.这基本上取决于你.
它可以极大地提高可读性,尤其是当您不想一直读取代码时触发智能感知(甚至更糟糕的是,查看打印输出).比较这两个:
CalculateBMI(123, 178); // What do the numbers mean?
CalculateBMI(weightInKg: 123, heightInCentimeters: 178); // Clearer IMHO.
Run Code Online (Sandbox Code Playgroud)
但是,通过一起使用命名参数和可选参数,您可以从可选参数列表中仅为少数参数提供参数.例如,此功能极大地方便了对COM接口的调用.
| 归档时间: |
|
| 查看次数: |
242 次 |
| 最近记录: |