我只是在msdn上查看Overloading Equals()指南(参见下面的代码); 大部分内容对我来说很清楚,但有一条线我没有得到.
if ((System.Object)p == null)
Run Code Online (Sandbox Code Playgroud)
或者,在第二次覆盖中
if ((object)p == null)
Run Code Online (Sandbox Code Playgroud)
为什么不简单
if (p == null)
Run Code Online (Sandbox Code Playgroud)
什么是反对购买我们的演员?
public override bool Equals(System.Object obj)
{
// If parameter is null return false.
if (obj == null)
{
return false;
}
// If parameter cannot be cast to Point return false.
TwoDPoint p = obj as TwoDPoint;
if ((System.Object)p == null)
{
return false;
}
// Return true if the fields match:
return (x == p.x) && (y …Run Code Online (Sandbox Code Playgroud) 我有一个重载operator==比较两个对象的类,但是当我检查该类型的对象时,null我在第一个参数上得到一个空引用异常.我想知道我应该如何防范这种情况,还是有另一种方法来实现这一点operator==
Card c;
if (c == null) { // do something } //null check throws exception cause c1 in operator has is a null object...
public static bool operator ==(Card c1, Card c2)
{
if (ReferenceEquals(c1, null) )
return false; // this does not make sense either I guess??
return c1.Equals(c2);
}
Run Code Online (Sandbox Code Playgroud)