2016-01-22 75 views
7

当我编写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); 
    } 
} 
+2

由于'Int32'从'Object',转换'Point'继承 - >'Int32'比'更具体Point' - >'Object',使得'Console.WriteLine(的Int32)'比'Console.WriteLine(Object)'更好。 – PetSerAl

+0

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

回答

8

的原因是由于隐式转换Int32(正如你可能知道)

Console.WriteLine有很多过载需要String,Object和其他包括Int32

由于Point隐式转换为Int32Console.WriteLineintoverload被使用,其确实的隐式转换为好。

这可以通过固定:

Console.WriteLine(new Point(1, 1).ToString()); 
Console.WriteLine((object)new Point(1, 1)); 

你可以找到更多关于它的Overload Resolution in C#

否则,最好功能部件是一个功能构件,其比所有其它的功能部件相对于所述给定 参数列表 更好,条件是每个功能部件与使用所有 其他函数成员规则Section 7.4.2.2

其还具有:

7.4.2.2 Better function member

每个参数,从AX到PX的隐式转换不 比从AX到QX的隐式转换差,

2

这是因为你的结构类型的隐式转换,即fol降脂行:

  public static implicit operator Int32(Point p) 
      { 
       Console.WriteLine("Converted to Int32"); 
       return p.y + p.x; 
      } 

因此,编译器正在考虑的点类型通过调用上述的隐式转换方法的整数。

要解决这个问题,就需要从您的类型中删除隐式转换或放一个ToString()方法,而这样做Console.WriteLine()

这应该可以解决您的问题。希望这可以帮助。

最佳