简体   繁体   English

为什么Object.ToString是虚拟方法?

[英]Why is Object.ToString a virtual method?

If it wasn't a virtual method, you can still achieve the same effect by just writing your ToString method normally, right? 如果它不是虚拟方法,则只需正常编写ToString方法就可以达到相同的效果,对吗?

You could even use the optional new keyword. 您甚至可以使用可选的new关键字。

Wouldn't this have better performance? 这会不会有更好的性能?

If it wasn't a virtual method, you can still achieve the same effect, by just writing your ToString method as normal, right? 如果它不是虚拟方法,则仍然可以通过正常编写ToString方法来达到相同的效果,对吗?

No. Consider (eg) the signature of (one overload of) the Console.WriteLine function: 否。考虑(例如) Console.WriteLine函数的签名(之一):

void Console.WriteLine(object o);

If ToString were novirtual, this would always call the System.Object.ToString implementation, not the one on the actual object passed to the function. 如果ToString是非虚拟的,则它将始终调用System.Object.ToString实现,而不是传递给该函数的实际对象上的那个。

Along the lines of Konrad's comment: 遵循Konrad的评论:

public Class A
{
    public new string ToString()
    {
        return "Hello from A";
    }
}

object a = new A();
a.ToString();

Would NOT return 'Hello from A' but instead would return the type name (which is what object's implementation does). 不会返回“来自A的Hello”,而是返回类型名称(这是对象的实现所执行的操作)。

You could ask the same of any virtual method. 您可以对任何虚拟方法提出相同的要求。

So this question is basically the same as asking "What is the purpose of virtual methods?" 因此,该问题与询问“虚拟方法的目的是什么?”基本相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM