您的位置:首页 > Web前端

Effective C#阅读笔记-4总是为你的类提供ToString()方法

2011-07-11 22:49 441 查看
Overriding Object.ToString() is the simplest way to provide a string representation of your classes. You should provide that every time you create a type. It should be the most obvious, most common representation of your type. On those rarer occasions when your type is expected to provide more sophisticated output, you should take advantage of implementing the IFormattable interface. It provides the standard way for users of your class to customize the text output for your type. If you leave these out, your users are left with implementing custom formatters. Those solutions require more code, and because users are outside of your class, they cannot examine the internal state of the object.Eventually, people consume the information in your types. People understand text output. Provide it in the simplest fashion possible: Override ToString() in all your types.Object.ToString()方法默认总是显示对象的类型名称,这个其实对类的使用者没有太多有价值的信息,为此我们应该重写,重写Object的ToString()方法,为我们的类提供有用的类信息。还可以实现 IFormattable接口,提供更为复杂的ToString()方法。

public virtual string ToString()
{
return this.GetType().ToString();
}


之所以要重写ToString()方法,主要是为了类的使用者可以清晰的知道类的相关信息描述。还是体现的面向对象的思想,在一个地方修改类,其他地方使用,而不是在每一个需要用到的地方在写个定制的ToString()方法。所以为你的每一个类都重写一个Object的ToString()方法,一劳永逸的事情。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: