该对象为null,但检查它是否返回false

时间:2014-05-13 11:02:00

标签: c#

我在C#4.5中遇到了一个奇怪的问题。

我的模型中有这个:

private DataMatrix<T> _matrix;

public DataMatrix<T> Matrix
{
    get { return _matrix; }
    set { _matrix = value; }
}

我有一个使用它的属性:

public object SingleElement
{
     get
     {
        if (Matrix == null) return String.Empty;

        if (Matrix.ColumnCount >= 1 && Matrix.RowCount >= 1)
        {
           return Matrix[0, 0];
        }
        return null;
     }
 }

当我运行它时,在调用SingleElement之前,Matrix属性为null。但它没有返回String.Empty,而是转到第二个if语句。

我的立即窗口说: Immediate window

我有点困惑。我做错了什么?

1 个答案:

答案 0 :(得分:6)

这很可能是一个破坏的等式运算符(==),可以使用以下代码重现:

class Foo
{
    public static bool operator == (Foo x, Foo y)
    {
        return false; // probably more complex stuff here in the real code
    }
    public static bool operator != (Foo x, Foo y)
    {
        return !(x == y);
    }
    static void Main()
    {
        Foo obj = null;
        System.Diagnostics.Debugger.Break();
    }
    // note there are two compiler warnings here about GetHashCode/Equals;
    // I am ignoring those for brevity
}

现在在即时窗口的断点处:

?obj
null
?(obj==null)
false

两个修正:

  • 首选修复操作符,可能先添加其他内容:

    if(ReferenceEquals(x,y)) return true;
    if((object)x == null || (object)y == null) return false;
    // the rest of the code...
    
  • 另外,如果你不能编辑那个类型,就是避免使用运算符;考虑在代码中明确使用ReferenceEquals,或执行基于object的{​​{1}}检查;例如:

    null

    if(ReferenceEquals(Matrix, null)) ...