为什么这样做:
// If parameter cannot be cast to Point return false.
TwoDPoint p = obj as TwoDPoint;
if ((System.Object)p == null)
{
return false;
}
取而代之的是:
// If parameter cannot be cast to Point return false.
TwoDPoint p = obj as TwoDPoint;
if (p == null)
{
return false;
}
我不明白你为什么要写 ((System.Object)p)?
问候,
丹
最佳答案
当你不知道或不能确定原始类是否覆盖了operator ==
时,你转换为object
:
using System;
class AlwaysEqual
{
public static bool operator ==(AlwaysEqual a, AlwaysEqual b)
{
return true;
}
public static bool operator !=(AlwaysEqual a, AlwaysEqual b)
{
return true;
}
}
class Program
{
static void Main()
{
object o = new AlwaysEqual();
AlwaysEqual ae = o as AlwaysEqual;
if (ae == null)
{
Console.WriteLine("ae is null");
}
if ((object)ae == null)
{
Console.WriteLine("(object)ae is null");
}
}
}
这段代码只输出 “ae is null”
,显然不是这样的。转换为 object
避免了 AlwaysEqual
类的 operator ==
,因此是针对 null
的真正引用检查。
关于c# - ((System.Object)p == null),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2908702/