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条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-03-23 02:46

C# doesn't require it; Resharper does. It requires it because the two keywords represent significantly different behavior, and if you don't specify, someone reading your code might not be entirely clear on which the default behavior is (it's new.)

In this case you clearly want to override.

查看更多
看我几分像从前
3楼-- · 2019-03-23 02:47

ToString is a virtual method in base class. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.

查看更多
我命由我不由天
4楼-- · 2019-03-23 02:50

You want to override. There's really no advantage to hiding in your case (using "new").

Here's an article on the differences between overriding and hiding.

查看更多
一夜七次
5楼-- · 2019-03-23 02:57

If you use public string ToString() it is unclear what you intended to do. If you mean to change the behaviour of ToString via polymorphism, then override. You could add a new ToString(), but that would be silly. Don't do that!

The difference is what happens when you do:

MyType t = new MyType();
object o = t;
Console.WriteLine(t.ToString());
Console.WriteLine(o.ToString());

If you override, both will output your new version. If you new, only the first will use your new version; the second will use the original implementation.

I don't think I've ever seen anybody use method hiding (aka new) on ToString().

查看更多
放荡不羁爱自由
6楼-- · 2019-03-23 03:00

A personal recommendation from me would be to not use hiding; it causes many ambiguities and solves few.

查看更多
兄弟一词,经得起流年.
7楼-- · 2019-03-23 03:02

What you do all depends on the behaviour you want. This article explains how the behaviour of ToString works depending on how you defined the method and what level in a class hierarchy you call ToString on.

查看更多
登录 后发表回答