它为什么/时,将覆盖的ToString是适当的? [英] Why / when would it be appropriate to override 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屋!