简体   繁体   中英

Difference between “Convert.ToString(Nullable<int>)” and “Nullable<int>.ToString()”?

i have a generally question about the conversion method ".ToString()". At first i use this statement for the conversion:

Nullable<int> SomeProperty;
string test = SomeProperty.ToString();

Up to here there is no problem but after that i want to add "CultureInfo.InvariantCulture" to the ToString() method. It doesn't work because the .ToString() of a Nullable has no parameters. Why does Resharper suggest to insert the CultureInfo informations to me??

After that i try a other way and use this statement:

Nullable<int> SomeProperty;
string test = Convert.ToString(SomeProperty, CultureInfo.InvariantCulture);

This statement works fine but now i want to understand the technical difference between the first and the second statement??

Convert.ToString Method (Object, IFormatProvider) :

If the value parameter implements the IConvertible interface, the method calls the IConvertible.ToString(IFormatProvider) implementation of value. Otherwise, if the value parameter implements the IFormattable interface, the method calls its IFormattable.ToString(String, IFormatProvider) implementation. If value implements neither interface, the method calls the value parameter's ToString() method.

Nullable<int> is seen like standard int , and IFormattable.ToString(String, IFormatProvider) is fired when Convert.ToString with format provider is called.

Proof:

class MyFormatProvider : IFormatProvider
{

    public object GetFormat(Type formatType)
    {
        return "G";
    }
}

static void Main(string[] args)
{
    Nullable<int> SomeProperty = 1000000;
    Console.WriteLine(SomeProperty.ToString());
    Console.WriteLine(Convert.ToString(SomeProperty));
    Console.WriteLine(Convert.ToString(SomeProperty, new MyFormatProvider()));
}

Put breakpoint within GetFormat and it's going to be hit when the last one of Main is executed.

read msdn http://msdn.microsoft.com/en-us/library/6t7dwaa5.aspx

The return value is formatted with the general numeric format specifier ("G") and the NumberFormatInfo object for the current culture.

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