我在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语句.
这是我的立即窗口说:

我有点困惑.我做错了什么?
这很可能是一个破坏的相等运算符(==),可以使用以下代码重现:
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)
两个修复:
首选是修复操作符,可能先添加其他内容:
if(ReferenceEquals(x,y)) return true;
if((object)x == null || (object)y == null) return false;
// the rest of the code...
Run Code Online (Sandbox Code Playgroud)另外,如果你不能编辑那种类型,就是避免使用运算符; 考虑ReferenceEquals在代码中明确使用,或执行object基于null检查的; 例如:
if(ReferenceEquals(Matrix, null)) ...
Run Code Online (Sandbox Code Playgroud)
要么
if((object)Matrix == null) ...
Run Code Online (Sandbox Code Playgroud)