重构:消除c# while循环中的代码重复

本文关键字:代码 循环 消除 while 重构 | 更新日期: 2023-09-27 18:12:23

为了消除A点和B点的代码重复,我有哪些选项可以重写以下代码段:

var value = source.GetNext(); // A
while (value != -1) 
{
    sum += value;
    value = source.GetNext(); // B
}

使用中循环断行重写是不可接受的:

while (true)
{
    int value = source.GetNext();
    if (value == -1) break;
    sum += value;
}

重构:消除c# while循环中的代码重复

Easy Easy:)

while ((value = source.GetNext()) != -1)
{
    sum += value;
}