C#:String.Format 是否调用输入的 ToString?

标签 c# string format

String.Format 是否运行 ToString?

例如,如果我有一个“复杂”类的对象,我可以这样做吗:

 <i>String.Format("String rep. {0}",complexObj);</i>

最佳答案

来自documentation :

如何格式化参数:

Format items are processed sequentially from the beginning of the string. Each format item has an index that corresponds to an object in the method's argument list. The Format method retrieves the argument and derives its string representation as follows:

  • 如果参数为null,该方法会将String.Empty 插入到结果字符串中。
  • 如果您调用 Format(IFormatProvider, String, Object[]) 重载并且提供者参数实现了 ICustomFormatter 接口(interface),该参数将传递给提供者对象的 ICustomFormatter.Format(String, Object, IFormatProvider) 方法。如果格式项包含 formatString 参数,它将作为第一个参数传递给该方法。如果 ICustomFormatter 实现能够提供格式化服务,它会返回参数的字符串表示;否则,它返回 null 并执行下一步。
  • 如果参数实现了 IFormattable 接口(interface),则调用其 IFormattable.ToString 实现。
  • 参数的无参数ToString 方法被调用。 重写或继承自 Object 类

是的,最后 - 作为回退 - ToString 方法被调用。

关于C#:String.Format 是否调用输入的 ToString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22940410/

相关文章:

csv - LibreOffice Calc : How to open CSV with numbers as text?

c# - WPF 中的类监听器和实例监听器有什么区别?

c# - AssemblyInfo 文件的版本控制和更新

c# - 在 C# 中访问消息元素的内部嵌套 JSON 数组

c# - 根据 npgsql 未找到字段,但根据 pgadmin 存在

c - 关于 strcmp() 的程序的 C 代码有什么问题?

python - 生成器可以在 python 中与 string.format 一起使用吗?

c++ - 带有字符显示的 vector

javascript - 无法使用数字键盘输入数字

c# - 从奇怪的格式解析 c# 中的 DateTime