Różnica między konwersją.ToString () oraz.ToString()

Jaka jest różnica między Convert.ToString() a .ToString()?

Znalazłem wiele różnic w Internecie, ale jaka jest główna różnica?

Author: animuson, 2010-05-13

13 answers

Convert.ToString() uchwyty null, natomiast ToString() nie.

 176
Author: Ryan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-19 14:15:09

Wywołanie ToString() Na obiekcie zakłada, że obiekt nie jest null (ponieważ obiekt musi istnieć, aby wywołać na nim metodę instancji). Convert.ToString(obj) nie musi zakładać, że obiekt nie jest null( ponieważ jest statyczną metodą na klasie Convert), ale zamiast tego zwróci String.Empty Jeśli jest null.

 48
Author: Chris Dwyer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-05-13 15:51:01

Pozwala zrozumieć różnicę w tym przykładzie:

int i= 0;
MessageBox.Show(i.ToString());
MessageBox.Show(Convert.ToString(i));

Możemy przekonwertować liczbę całkowitą i używając i.ToString () lub Convert.ToString. Więc co za różnica?

Podstawową różnicą między nimi jest to, że Convert Funkcja obsługuje null, podczas gdy i.ToString () nie; spowoduje to błąd wyjątku odniesienia NULL. Tak więc dobra praktyka kodowania przy użyciu {[6] } jest zawsze bezpieczna.

 9
Author: Swati,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-06 15:32:40

Oprócz innych odpowiedzi na temat obsługi wartości null, Convert.ToString próbuje użyć interfejsów IFormattable i IConvertible przed wywołaniem base Object.ToString.

Przykład:

class FormattableType : IFormattable
{
    private double value = 0.42;

    public string ToString(string format, IFormatProvider formatProvider)
    {
        if (formatProvider == null)
        {
            // ... using some IOC-containers
            // ... or using CultureInfo.CurrentCulture / Thread.CurrentThread.CurrentCulture
            formatProvider = CultureInfo.InvariantCulture;
        }

        // ... doing things with format
        return value.ToString(formatProvider);
    }

    public override string ToString()
    {
        return value.ToString();
    }
}

Wynik:

Convert.ToString(new FormattableType()); // 0.42
new FormattableType().ToString();        // 0,42
 8
Author: Alexander,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-04 15:39:58

Możesz utworzyć klasę i nadpisać metodę toString, aby zrobić wszystko, co chcesz.

Na przykład - możesz utworzyć klasę "MyMail" i nadpisać metodę toString, aby wysłać wiadomość e-mail lub wykonać inną operację zamiast pisać bieżący obiekt.

Convert.toString zamienia podaną wartość na równoważną reprezentację łańcuchową.

 4
Author: user2039962,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-08 15:13:47
object o=null;
string s;
s=o.toString();
//returns a null reference exception for string  s.

string str=convert.tostring(o);
//returns an empty string for string str and does not throw an exception.,it's 
//better to use convert.tostring() for good coding
 3
Author: sudeep,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-13 07:34:59

W Convert.ToString(), konwerter obsługuje wartość NULL lub nie, ale w .ToString() nie obsługuje wartości NULL i błędu wyjątku NULL. Tak więc w dobrej praktyce jest stosowanie Convert.ToString().

 2
Author: Ajay Saini,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-03 12:14:39

Dla miłośników kodu jest to najlepsza odpowiedź.

    .............. Un Safe code ...................................
    Try
        ' In this code we will get  "Object reference not set to an instance of an object." exception
        Dim a As Object
        a = Nothing
        a.ToString()
    Catch ex As NullReferenceException
        Response.Write(ex.Message)
    End Try


    '............... it is a safe code..............................
    Dim b As Object
    b = Nothing
    Convert.ToString(b)
 2
Author: Abdul Saboor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-17 11:19:32

Metody są "zasadniczo" takie same, z wyjątkiem obsługi null .

Pen pen = null; 
Convert.ToString(pen); // No exception thrown
pen.ToString(); // Throws NullReferenceException

Z MSDN :
Nawróć się.Metoda ToString

Konwertuje podaną wartość na jej równoważną reprezentację łańcuchową.

Obiekt.ToString

Zwraca łańcuch reprezentujący bieżący obiekt.

 2
Author: hdoghmen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-11 09:27:07

Zgadzam się z @Ryan'odpowiedz. Przy okazji, począwszy od C # 6.0 do tego celu można użyć:

someString?.ToString() ?? string.Empty;

Lub

$"{someString}"; // I do not recommend this approach, although this is the most concise option.

Zamiast

Convert.ToString(someString);
 2
Author: AndreyWD,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-18 12:44:18

ToString() nie może obsługiwać wartości null i convert.ToString() może obsługiwać wartości, które są null, więc jeśli chcesz, aby Twój system obsługiwał wartość null, użyj convert.ToString().

 1
Author: viplov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-05 11:41:12

Convert.ToString(strName) będzie obsługiwał wartości NULL, a strName.Tostring() nie będzie obsługiwał wartości null i wyrzuci wyjątek.

Więc lepiej użyć Convert.ToString() wtedy .ToString();

 1
Author: Gaurang Dhandhukiya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-12 12:38:42
ToString() Vs Convert.ToString()

Podobieństwa: -

Oba są używane do konwersji określonego typu NA string czyli int na string, float na string lub obiekt na string.

Różnica: -

ToString() can ' t handle null while in case with Convert.ToString() will handle null value.

Przykład:

namespace Marcus
{
    class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    class Startup
    {
        public static void Main()
        {
            Employee e = new Employee();
            e = null;

            string s = e.ToString(); // This will throw an null exception
            s = Convert.ToString(e); // This will throw null exception but it will be automatically handled by Convert.ToString() and exception will not be shown on command window.
        }
    }
}
 1
Author: Johnny,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-19 10:11:13