C# 条件语句和如何递增变量

C# 条件语句和如何递增变量,c#,increment,conditional-statements,C#,Increment,Conditional Statements,我有以下代码: public static int Compute(string a, string b, bool ignoreCase) { // Allocate distance matrix int[,] d = new int[a.Length + 1, b.Length + 1]; // Get character comparer CharComparer isEqual = (ignoreCase) ? (CharCompare

我有以下代码:

public static int Compute(string a, string b, bool ignoreCase)
{
    // Allocate distance matrix
    int[,] d = new int[a.Length + 1, b.Length + 1];

    // Get character comparer
    CharComparer isEqual = (ignoreCase) ?
        (CharComparer)CharCompareIgnoreCase : CharCompare;

    // Compute distance
    for (int i = 0; i <= a.Length; i++)
        d[i, 0] = i;
    for (int j = 0; j <= b.Length; j++)
        d[0, j] = j;
    for (int i = 1; i <= a.Length; i++)
    {
        for (int j = 1; j <= b.Length; j++)
        {
            if (isEqual(a[i - 1], b[j - 1]))
            {
                // No change required
                d[i, j] = d[i - 1, j - 1];
            }
            else
            {
                d[i, j] =
                  Math.Min(d[i - 1, j] + 1, // Deletion
                  insertions=  Math.Min(d[i, j - 1] + 1,    // Insertion
                   substitutions= d[i - 1, j - 1] + 1));       // Substitution
            }
        }
    }

但是,正如埃里克所说的那样,只是运气不好:将声明拆分为多个声明

    else
    {
        substitutions = d[i - 1, j - 1] + 1;
        insertions =  Math.Min(d[i, j - 1] + 1, substitutions);
        deletion = Math.Min(d[i - 1, j] + 1, insertions);
        d[i, j] = deletion;

        if (/* whatever */)
            counter++;
    }

我很确定它会像以前一样做同样的事情,但我不知道你想算什么,因为所有的行都会被执行。

我同意@Eric和@usr,但如果你想在一个语句中做到这一点(我知道一行的心态,我自己就是它的受害者!),你可以这样做(免责声明:我还没有测试过):

++增加插入值并返回新值。因此它将类似于x-x=0,因此不会影响较大的语句

编辑


对不起,伙计们。这个解决方案只适用于三元运算符,它执行短路,而OP的问题使用函数调用,因此每次都会求值,从而扼杀计数器的用途。

这样混合计算和副作用是一种非常糟糕的编程实践;它使代码很难读取。如果你想执行一个计算,执行一个计算,然后增加计数器。Eric是对的:只要将这个怪物的单个语句重组为多个语句,你就会很容易实现你的目标!如果它变得太复杂以至于你无法理解-简化。虽然这样的怪物很有趣,但它总是会评估不需要的增量。
    else
    {
        substitutions = d[i - 1, j - 1] + 1;
        insertions =  Math.Min(d[i, j - 1] + 1, substitutions);
        deletion = Math.Min(d[i - 1, j] + 1, insertions);
        d[i, j] = deletion;

        if (/* whatever */)
            counter++;
    }
Math.Min(d[i, j - 1] + 1 + (++insertion - insertion)