当我编写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