[英]Does Convert.ChangeType call ToString() internally?
Is there any difference between:有什么区别:
value.ToString()
and和
(string)Convert.ChangeType(value, typeof(string))
It calls the IConvertable.ToString
after ensuring the types are IConvertable
.它在确保类型为
IConvertable.ToString
后调用IConvertable
。
case TypeCode.String:
return (object) convertible.ToString(provider);
So as a result, its doing a lot more work just to call ToString
with an IFormatProvider
.因此,它做更多的工作只是用
IFormatProvider
调用ToString
。 It will all depend on the implementation of the type that implements IConvertable
.这一切都取决于实现
IConvertable
的类型的实现。
The provider
comes from (IFormatProvider) Thread.CurrentThread.CurrentCulture
. provider
来自(IFormatProvider) Thread.CurrentThread.CurrentCulture
。
This is what int
does.这就是
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));
}
when target type is string, Convert.ChangeType works like this:当目标类型为字符串时,Convert.ChangeType 的工作方式如下:
if (value == null)
{
return null;
}
var convertible = value as IConvertible;
if (convertible == null)
{
throw new InvalidCastException();
}
return convertible.ToString();
so it's quite different from value.ToString();所以它与 value.ToString(); 完全不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.