Mat*_*ias 4 c# operator-overloading
我只是在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 == p.y);
}
public bool Equals(TwoDPoint p)
{
// If parameter is null return false:
if ((object)p == null)
{
return false;
}
// Return true if the fields match:
return (x == p.x) && (y == p.y);
}
Run Code Online (Sandbox Code Playgroud)
Mic*_*tta 11
该==
运营商可能会被改写,如果是,则默认基准比较可能不是你所得到的.转换为System.Object可确保调用==
执行引用相等性测试.
public static bool operator ==(MyObj a, MyObj b)
{
// don't do this!
return true;
}
...
MyObj a = new MyObj();
MyObj b = null;
Console.WriteLine(a == b); // prints true
Console.WriteLine((object)a == (object)b); // prints false
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
657 次 |
最近记录: |