我尝试覆盖 != 运算符:
public class Box
{
public Box()
{
}
public Box(double height, double width)
{
Height = height;
Width = width;
}
public double Height { get; set; }
public double Width { get; set; }
public override int GetHashCode()
{
unchecked
{
return (Height.GetHashCode() * 397) ^ Width.GetHashCode();
}
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == GetType() && Equals((Box)obj);
}
protected bool Equals(Box other)
{
return Math.Abs(Height - other.Height) + Math.Abs(Width - other.Width) < 0.001;
}
public static bool operator ==(Box left, Box right)
{
if (ReferenceEquals(null, left))
return false;
if (ReferenceEquals(null, right))
return false;
return left.Equals(right);
}
public static bool operator !=(Box left, Box right)
{
var t = !(left == right);
return t;
}
}
public class BetterBox:Box{
}
并尝试使用 != 运算符
var box = new Box();
var betterBox = box as BetterBox;
if(betterBox!=null){
--do-something
}
在这种情况下 != returntrue并且代码进入if. 这里有什么问题?为什么会发生?
在 mdsn 我看到相同的代码:https ://docs.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/336aedhh%28v%3dvs.100%29
BIG阳
慕姐8265434
千巷猫影
随时随地看视频慕课网APP
相关分类