【问题标题】:Better Coding Practice Than If-Else比 If-Else 更好的编码实践
【发布时间】:2016-11-16 06:35:31
【问题描述】:

假设我有这个代码。

int count = 0;
int id = GetFirstId();
count = getCountById(id);

if(count == 0){
 id = GetSecondId();
 count = getCountById(id);
  if(count == 0){
    id = GetThirdId();
    count = getCountById(id);
  }
}

有没有更好的方法来做到这一点。内部的 LOOP 和 CASE 语句之类的东西更好吗?

【问题讨论】:

  • 您使用的是什么编程语言?
  • C# 但我认为这种做法也应该应用于其他编程语言?
  • 如果您有很多物品,您绝对应该使用开关。

标签: c# if-statement logic


【解决方案1】:

如果您有不同的方法,您可以列出这些方法,然后使用 LINQ 获取第一个非零 count。如果您的GetXXXId所有都具有相同的签名,它将起作用。

var idGetters = new Func<int>[] 
{
    GetFirstId,
    GetSecondId,
    GetThirdId
    // and so on
};

var count = idGetters
            .Select(x => x())
            .Select(GetCountById)
            .SkipWhile(x => x == 0)
            .FirstOrDefault();

【讨论】:

  • 如果 Id 不递增怎么办。我应该在循环内使用 case 吗?然后有类似 Case(i): id = 15
  • 我已经编辑了这个问题。顺便谢谢你的回答!
  • 好的!我非常喜欢这个解决方案,它是动态的。谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-10
相关资源
最近更新 更多