[英]Does Convert.ChangeType call ToString() internally?
有什么区别:
value.ToString()
和
(string)Convert.ChangeType(value, typeof(string))
它在确保类型为IConvertable.ToString
后调用IConvertable
。
case TypeCode.String:
return (object) convertible.ToString(provider);
因此,它做更多的工作只是用IFormatProvider
调用ToString
。 这一切都取决于实现IConvertable
的类型的实现。
provider
来自(IFormatProvider) Thread.CurrentThread.CurrentCulture
。
这就是int
的作用。
public override string ToString()
{
return Number.FormatInt32(this, (string) null, NumberFormatInfo.CurrentInfo);
}
public string ToString(string format)
{
return Number.FormatInt32(this, format, NumberFormatInfo.CurrentInfo);
}
public string ToString(IFormatProvider provider)
{
return Number.FormatInt32(this, (string) null, NumberFormatInfo.GetInstance(provider));
}
public string ToString(string format, IFormatProvider provider)
{
return Number.FormatInt32(this, format, NumberFormatInfo.GetInstance(provider));
}
当目标类型为字符串时,Convert.ChangeType 的工作方式如下:
if (value == null)
{
return null;
}
var convertible = value as IConvertible;
if (convertible == null)
{
throw new InvalidCastException();
}
return convertible.ToString();
所以它与 value.ToString(); 完全不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.