C#: public new string ToString() VS public overrid

2019-03-23 02:35发布

I want to redefine the ToString() function in one of my classes.

I wrote

public string ToString()

... and it's working fine. But ReSharper is telling me to change this to either

public new string ToString() 

or

public override string ToString()

What's the difference? Why does C# requires something like this?

标签: c# oop
9条回答
【Aperson】
2楼-- · 2019-03-23 03:05

The new modifier will hide or "shadow" the member with the same signature in the base class where as overriding provides a new implementation of a member inherited from a base class. Here is a good article on the differences between shadowing and overriding.

查看更多
贪生不怕死
3楼-- · 2019-03-23 03:10

The problem is that ToString is a virtual method. In order to override a virtual method in C# you need to specify the override keyword.

You almost certainly do not want the "new" version. .

查看更多
欢心
4楼-- · 2019-03-23 03:10

ToString() method is available for every type in .NET, as this method is defined as a virtual method in the base System.Object class, and all types directly or indirectly inherit from System.Object. If the default implementation of ToString() method doesn't server your purpose, you may wish to override (use override keyword) or hide (use new keyword) it.

I have come across the following 2 excellent articles explaining the reasons to override ToString() method, and the difference between method hiding and method overriding. There is also a youtube video on the same concepts
Reason to override ToString()
Difference between method hiding and method overriding

查看更多
登录 后发表回答