简体   繁体   中英

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 .

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 . It will all depend on the implementation of the type that implements IConvertable .

The provider comes from (IFormatProvider) Thread.CurrentThread.CurrentCulture .

This is what int does.

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:


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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM