比其他更好的编码实践

时间:2016-11-16 06:35:31

标签: c# if-statement logic

假设我有这段代码。

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声明更好吗?

1 个答案:

答案 0 :(得分:4)

如果您有不同的方法,可以列出方法,然后使用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();