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/