使用转换方法覆盖类型中的虚方法

YV1*_*V17 7 .net c#

当我写 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Hab*_*bib 8

原因是由于隐式转换为Int32 (您可能知道).

Console.WriteLine有许多重载需要String,Object其他包括Int32.

由于Point隐式转换为Int32所述int 过载Console.WriteLine被使用,其确实的隐式转换为好.

这可以通过以下方式解决:

Console.WriteLine(new Point(1, 1).ToString());
Console.WriteLine((object)new Point(1, 1));
Run Code Online (Sandbox Code Playgroud)

您可以在C#中的Overload Resolution中找到更多相关信息.

否则,最好的函数成员是一个函数成员,它比给定参数列表中的所有其他函数成员更好,只要使用第7.4.2.2节中的规则将每个函数成员与所有其他函数成员进行比较.

还有哪些:

7.4.2.2更好的功能成员

对于每个参数,隐式转换从AX到PX不大于从AX到QX的隐式转换差,和