C#:应该如何的ToString()来实现? [英] C#: How should ToString() be implemented?

查看:424
本文介绍了C#:应该如何的ToString()来实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的问题是:


  • GUI库喜欢用的ToString 作为上课默认表示。在那里,它需要本地化。

  • 的ToString 用于记录。在那里,它应该提供编程相关的信息,是不是翻译,包括像代理键和枚举值的内部状态。

  • 的ToString 所使用的许多字符串操作,内搭的对象作为参数,例如的String.Format ,写流时。根据上下文你期望不同的东西。

  • 的ToString 是太多,如果有同一对象的许多不同的表述,限制如。长和短形式。

  • GUI libraries like to use ToString as a default representation for classes. There it needs to be localized.
  • ToString is used for logging. There it should provide programming related information, is not translated and includes internal states like surrogate keys and enum values.
  • ToString is used by many string operations which take objects as arguments, for instance String.Format, when writing to streams. Depending on the context you expect something different.
  • ToString is too limited if there are many different representations of the same object, eg. a long and a short form.

由于在不同的用途,有许多不同种类的实现。因此,他们太不可靠是非常有用的。

Because of the different usages, there are many different kinds of implementation. So they are too unreliable to be really useful.

应该如何的ToString 实施是有用的?当应的ToString 使用时,它应该是可以避免的?

How should ToString be implemented to be useful? When should ToString be used, when should it be avoided?


借助 .NET Framework文档说:

这方法返回一个人类可读的
字符串,它是文化的敏感

This method returns a human-readable string that is culture-sensitive.

有一个的类似的问题,但不一样的。

There is a similar question, but not the same.

推荐答案

看来你已经从一个小小的方法寄予厚望: )据我知道这不是用一般的方法在很多不同的情况下特别是当其行为可以从类别不同类是一个好主意。

It seems you have great expectations from a tiny little method :) As far as I know it's not a good idea to use a general method in so many different contexts specially when its behavior can differ from class to class.

下面是我的建议:

1.Do不让GUI库使用objects.Instead的toString()方法使用更有意义的属性(几乎所有的控件可以定制显示等性能比的ToString )
例如使用的DisplayMember。
2,当获得有关对象的一些信息(用于记录或其他用途),让别人决定(另一种对象或对象本身)应该提供什么,以及应该如何显示。(A战略格局可能会派上用场)

1.Do not let GUI libraries use ToString() of your objects.Instead use more meaningful properties (Almost all controls can be customized to show other properties than ToString) for example use DisplayMember. 2.When getting some information about an object (for logging or other usages) let somebody decide (another object or the object itself)what should be provided and how it should be displayed.(A strategy pattern may come in handy)

这篇关于C#:应该如何的ToString()来实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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