C#:公共新字符串ToString()VS公共重写字符串ToString() [英] C#: public new string ToString() VS public override string ToString()

查看:124
本文介绍了C#:公共新字符串ToString()VS公共重写字符串ToString()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的一个类中重新定义ToString()函数.

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

我写了

public string ToString()

...并且工作正常.但是ReSharper告诉我将其更改为

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

public new string ToString() 

public override string ToString()

有什么区别?为什么C#需要这样的东西?

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

推荐答案

如果您使用public string ToString(),则不清楚您打算做什么.如果要通过多态性更改ToString的行为,请使用override.您可以添加new ToString(),但这很愚蠢.不要那样做!

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());

如果您override,则两者都将输出您的新版本.如果您new,则只有第一个会使用您的新版本;否则,请使用第一个版本.第二个将使用原始实现.

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.

我认为我从未看到有人在ToString()上使用隐藏方法(又名new).

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

这篇关于C#:公共新字符串ToString()VS公共重写字符串ToString()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆