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

erm*_*erd 4 c#

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

我的模型中有这个:

private DataMatrix<T> _matrix;

public DataMatrix<T> Matrix
{
    get { return _matrix; }
    set { _matrix = value; }
}
Run Code Online (Sandbox Code Playgroud)

我有一个使用这个的属性:

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

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

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

这是我的立即窗口说: 即时窗口

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

Mar*_*ell 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
}
Run Code Online (Sandbox Code Playgroud)

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

?obj
null
?(obj==null)
false
Run Code Online (Sandbox Code Playgroud)

两个修复: