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

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()方法,一劳永逸的事情。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值