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()方法。
之所以要重写ToString()方法,主要是为了类的使用者可以清晰的知道类的相关信息描述。还是体现的面向对象的思想,在一个地方修改类,其他地方使用,而不是在每一个需要用到的地方在写个定制的ToString()方法。所以为你的每一个类都重写一个Object的ToString()方法,一劳永逸的事情。
public virtual string ToString() { return this.GetType().ToString(); }
之所以要重写ToString()方法,主要是为了类的使用者可以清晰的知道类的相关信息描述。还是体现的面向对象的思想,在一个地方修改类,其他地方使用,而不是在每一个需要用到的地方在写个定制的ToString()方法。所以为你的每一个类都重写一个Object的ToString()方法,一劳永逸的事情。
相关文章推荐
- 条款5:总是提供ToString()方法
- Effective C# Item5:总是提供ToString()方法
- 《Effective C#》读书笔记——条目5:为类型提供ToString()方法<C#语言习惯>
- 总是提供ToString()方法
- 条款5:总是提供ToString()方法
- Effective C# Item5:总是提供ToString()方法
- 条款5:总是提供ToString()方法
- 改善C#程序的50种方法 条款5:总是提供ToString()方法
- Effective C# 学习笔记(五) 最好重载你所创建类的ToString()方法
- 熊猫书院DAY4笔记——《如何阅读一本书》之阅读不同读物的方法(二)
- 论文阅读笔记之ICML2012::The Landmark Selection Method for Multiple Output Prediction 基于代表性特征选取的多维度回归方法
- Java三大集合类源码阅读笔记【包含超类Collection】提供学习源码
- 阅读笔记——基于字典学习的图像分类方法总结
- 文献阅读----《病理语音的 S 变换特征及其提取方法》(笔记篇)
- 笨方法学python(本文为阅读时从此书摘录的笔记) 第一天
- Effective C# 学习笔记(七) 重载GetHashCode()方法要小心
- 论文阅读笔记之ICML2012::The Landmark Selection Method for Multiple Output Prediction 基于代表性特征选取的多维度回归方法
- C#框架阅读笔记--equals方法
- IO篇二( IO典型的使用方法 thinking in java 4th 阅读笔记)
- 笨方法学python(本文为阅读时从此书摘录的笔记) 第二天