为什么这个Int32总和总是返回0?

时间:2015-01-12 23:11:44

标签: .net integer

我知道至少有一个值不是零,而且总和仍然是0 为什么?

get 
{
    Debug.WriteLine("ILockSumN");
    Debug.WriteLine(iLocks[2, 1] == (Int32?)null ? 0 : (Int32)iLocks[2, 1]);
    Debug.WriteLine(iLocks[3, 1] == (Int32?)null ? 0 : (Int32)iLocks[3, 1]);
    Debug.WriteLine(iLocks[6, 1] == (Int32?)null ? 0 : (Int32)iLocks[6, 1]);
    Int32 sum =
        iLocks[1, 1] == (Int32?)null ? 0 : (Int32)iLocks[1, 1] +
        iLocks[2, 1] == (Int32?)null ? 0 : (Int32)iLocks[2, 1] +
        iLocks[3, 1] == (Int32?)null ? 0 : (Int32)iLocks[3, 1] +
        iLocks[4, 1] == (Int32?)null ? 0 : (Int32)iLocks[4, 1] +
        iLocks[5, 1] == (Int32?)null ? 0 : (Int32)iLocks[5, 1] +
        iLocks[6, 1] == (Int32?)null ? 0 : (Int32)iLocks[6, 1];
    Debug.WriteLine(sum);
    return sum; 
} 

3 个答案:

答案 0 :(得分:3)

似乎是一个优先级问题 - 基本上如果iLocks[1, 1]null则需要0,否则它会使用另一个具有所有添加项的分支。

尝试添加括号:

Int32 sum =
    (iLocks[1, 1] == (Int32?)null ? 0 : (Int32)iLocks[1, 1]) +
    (iLocks[2, 1] == (Int32?)null ? 0 : (Int32)iLocks[2, 1]) +
    (iLocks[3, 1] == (Int32?)null ? 0 : (Int32)iLocks[3, 1]) +
    (iLocks[4, 1] == (Int32?)null ? 0 : (Int32)iLocks[4, 1]) +
    (iLocks[5, 1] == (Int32?)null ? 0 : (Int32)iLocks[5, 1]) +
    (iLocks[6, 1] == (Int32?)null ? 0 : (Int32)iLocks[6, 1]);

7.12 Conditional operator说:

  

条件运算符是右关联的,这意味着操作从右到左分组。例如,形式为a的表达式? b:c? d:e被评估为? b:(c?d:e)。

答案 1 :(得分:2)

学术LINQ示例:

private IEnumerable<T> GetItems<T>(int j, T[,] array)
{
    var length = array.GetLength(0);
    for (int i = 0; i < length; i++)
    {
        yield return array[i, j];
    }
}

用法:

var sum = GetItems(1, iLocks)
    .Where(i => i != null)
    .Sum() ?? 0;

答案 2 :(得分:2)

添加括号后,null coalescing运算符也会起作用(如迈克尔所述):

Int32 sum =
    (iLocks[1, 1] ?? 0) +
    (iLocks[2, 1] ?? 0) +
    (iLocks[3, 1] ?? 0) +
    (iLocks[4, 1] ?? 0) +
    (iLocks[5, 1] ?? 0) +
    (iLocks[6, 1] ?? 0);

或者,只是为了踢,与LINQ结合:

Int32 sum = Enumerable.Range(1,6).Select(i => iLocks[i,1] ?? 0).Sum();