它为什么/时,将覆盖的ToString是适当的? [英] Why / when would it be appropriate to override ToString?

查看:84
本文介绍了它为什么/时,将覆盖的ToString是适当的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学习C#,我不知道还有什么意义和压倒一切的利益的ToString 可能是,如下面的例子。

这会是一些比较简单的方式完成,采用通用的方法,无需覆盖?

 公共字符串GetToStringItemsHeadings
{
    {返回的String.Format({0,-20} {1,} -20,办公室通过电子邮件将,私人电子邮件); }
}
公共重写字符串的ToString()
{
    字符串斯特劳特=的String.Format({0,-20} {1,} -20,m_work,m_personal);
    返回斯特劳特;
}


解决方案

  • 你需要重写的ToString


  • 您可以得到一个字符串再以另一种方式的对象presentation?


但是,通过使用的ToString 您使用的是常见的一种方法的的所有对象的,因此其他类知道这个方法。例如,每当NET框架想要的对象转换为字符串再presentation,的ToString 是一个总理候选人(还有其他的,如果你想提供更复杂的格式选项)。

具体而言,

  Console.WriteLine(yourObject);

将调用 yourObject.ToString()

I'm studying C# and I wonder what the point and benefit of overriding ToString might be, as shown in the example below.

Could this be done in some simpler way, using a common method without the override?

public string GetToStringItemsHeadings
{
    get { return string.Format("{0,-20} {1, -20}", "Office Email", "Private Email"); }
}


public override string ToString()
{
    string strOut = string.Format("{0,-20} {1, -20}", m_work, m_personal);
    return strOut;
}

解决方案

  • Do you need to override ToString? No.

  • Can you get a string representation of your object in another way? Yes.

But by using ToString you are using a method that is common to all objects and thus other classes know about this method. For instance, whenever the .NET framework wants to convert an object to a string representation, ToString is a prime candidate (there are others, if you want to provide more elaborate formatting options).

Concretely,

Console.WriteLine(yourObject);

would invoke yourObject.ToString().

这篇关于它为什么/时,将覆盖的ToString是适当的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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