2016-01-22 73 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()

這應該可以解決您的問題。希望這可以幫助。

最佳