當我編寫Console.WriteLine(new Point (1,1));
時,它不會調用方法ToString
。但它將對象轉換爲Int32
,並將其寫入控制檯。但爲什麼?它似乎忽略了重寫方法ToString
。用轉換方法覆蓋虛擬方法
struct Point
{
public Int32 x;
public Int32 y;
public Point(Int32 x1,Int32 y1)
{
x = x1;
y = y1;
}
public static Point operator +(Point p1, Point p2)
{
return new Point(p1.x + p2.x, p1.y + p2.y);
}
public static implicit operator Int32(Point p)
{
Console.WriteLine("Converted to Int32");
return p.y + p.x;
}
public override string ToString()
{
return String.Format("x = {0} | y = {1}", x, y);
}
}
由於'Int32'從'Object',轉換'Point'繼承 - >'Int32'比'更具體Point' - >'Object',使得'Console.WriteLine(的Int32)'比'Console.WriteLine(Object)'更好。 – PetSerAl
Console.WriteLine(new Point(1,1));'?的實際輸出是什麼? [根據MSDN](https://msdn.microsoft.com/en-us/library/swx4tc5e(v = vs.110).aspx),它應該在傳遞的對象上調用'ToString()'。你確定它使用你的'Point'結構而不是默認的'System.Drawing.Point'結構嗎? – sab669