简体   繁体   English

Convert.ToString() 和.ToString() 之间的区别

[英]Difference between Convert.ToString() and .ToString()

What is the difference between Convert.ToString() and .ToString() ? Convert.ToString().ToString()有什么区别?

I found many differences online, but what's the major difference?我在网上发现了很多不同之处,但主要区别是什么?

Convert.ToString() handles null , while ToString() doesn't. Convert.ToString()处理null ,而ToString()没有。

Calling ToString() on an object presumes that the object is not null (since an object needs to exist to call an instance method on it).在 object 上调用ToString()假定 object 不是 null(因为 ZA8CFDE63311 上的一个实例方法需要调用它)。 Convert.ToString(obj) doesn't need to presume the object is not null (as it is a static method on the Convert class), but instead will return String.Empty if it is null. Convert.ToString(obj) doesn't need to presume the object is not null (as it is a static method on the Convert class), but instead will return String.Empty if it is null.

In addition to other answers about handling null values, Convert.ToString tries to use IFormattable and IConvertible interfaces before calling base Object.ToString .除了有关处理null值的其他答案之外, Convert.ToString在调用基本Object.ToString之前尝试使用IFormattableIConvertible接口。

Example:例子:

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

Result:结果:

Convert.ToString(new FormattableType()); // 0.42
new FormattableType().ToString();        // 0,42

Lets understand the difference via this example:让我们通过这个例子来理解区别:

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

We can convert the integer i using i.ToString () or Convert.ToString .我们可以使用i.ToString ()Convert.ToString转换 integer i So what's the difference?那么有什么区别呢?

The basic difference between them is the Convert function handles NULLS while i.ToString () does not;它们之间的基本区别是Convert function 处理 NULLS 而i.ToString ()不处理; it will throw a NULL reference exception error.它将抛出 NULL 引用异常错误。 So as good coding practice using convert is always safe.因此,使用convert的良好编码习惯始终是安全的。

You can create a class and override the toString method to do anything you want.您可以创建一个 class 并覆盖toString方法来做任何你想做的事情。

For example- you can create a class "MyMail" and override the toString method to send an email or do some other operation instead of writing the current object.例如,您可以创建 class “MyMail”并覆盖toString方法以发送 email 或执行其他操作,而不是写入当前的 object。

The Convert.toString converts the specified value to its equivalent string representation. Convert.toString将指定的值转换为其等效的字符串表示形式。

The methods are "basically" the same, except handling null .除了处理null之外,这些方法“基本”相同。

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

From MSDN:来自 MSDN:
Convert.ToString Method Convert.ToString 方法

Converts the specified value to its equivalent string representation.将指定的值转换为其等效的字符串表示形式。

Object.ToString Object.ToString

Returns a string that represents the current object.返回表示当前 object 的字符串。

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

I agree with @ Ryan 's answer.我同意@Ryan的回答。 By the way, starting with C#6.0 for this purpose you can use:顺便说一句,从 C#6.0 开始,您可以使用:

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

or或者

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

instead of代替

Convert.ToString(someString);

For Code lovers this is the best answer.对于代码爱好者来说,这是最好的答案。

    .............. 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)

Convert.ToString(strName) will handle null-able values and strName.Tostring() will not handle null value and throw an exception. Convert.ToString(strName)将处理可为空的值,而strName.Tostring()将不处理 null 值并引发异常。

So It is better to use Convert.ToString() then .ToString();所以最好使用Convert.ToString()然后.ToString();

In Convert.ToString() , the Convert handles either a NULL value or not but in .ToString() it does not handles a NULL value and a NULL reference exception error.Convert.ToString()中,Convert 处理NULL值或不处理,但在.ToString()中,它不处理NULL值和NULL引用异常。 So it is in good practice to use Convert.ToString() .因此,使用Convert.ToString()是一种很好的做法。

ToString() can not handle null values and convert.ToString() can handle values which are null, so when you want your system to handle null value use convert.ToString() . ToString()无法处理 null 值,而convert.ToString()可以处理 null 的值,因此当您希望系统处理 null 值时,请使用convert.ToString()

ToString() Vs Convert.ToString()

Similarities:-相似之处:-

Both are used to convert a specific type to string ie int to string, float to string or an object to string.两者都用于将特定类型转换为字符串,即 int 到 string、float 到 string 或 object 到 string。

Difference:-区别:-

ToString() can't handle null while in case with Convert.ToString() will handle null value. ToString()无法处理 null 而如果使用Convert.ToString()将处理 null 值。

Example:例子:

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.
        }
    }
}

Here both the methods are used to convert the string but the basic difference between them is: Convert function handles NULL , while i.ToString() does not it will throw a NULL reference exception error.这里两种方法都用于转换字符串,但它们之间的基本区别是: Convert function 处理NULL ,而i.ToString()没有它会抛出NULL reference exception error. So as good coding practice using convert is always safe.因此,使用convert的良好编码习惯始终是安全的。

Let's see example:让我们看一个例子:

string s;
object o = null;
s = o.ToString(); 
//returns a null reference exception for s. 

string s;
object o = null;
s = Convert.ToString(o); 
//returns an empty string for s and does not throw an exception.

Convert.ToString(value) first tries casting obj toIConvertible , thenIFormattable to call corresponding ToString(...) methods. Convert.ToString(value)首先尝试将 obj 转换为IConvertible ,然后IFormattable调用相应的ToString(...)方法。 If instead the parameter value was null then return string.Empty .如果参数值为null则返回string.Empty As a last resort, return obj.ToString() if nothing else worked.作为最后的手段,如果没有其他方法,请返回obj.ToString()

It's worth noting that Convert.ToString(value) can return null if for example value.ToString() returns null.值得注意的是, Convert.ToString(value)可以返回null ,例如value.ToString()返回 null。

See .Net reference source请参阅.Net 参考源

i wrote this code and compile it.我写了这段代码并编译它。

class Program
{
    static void Main(string[] args)
    {
        int a = 1;
        Console.WriteLine(a.ToString());
        Console.WriteLine(Convert.ToString(a));
    }
}

by using 'reverse engineering' ( ilspy ) i find out 'object.ToString()' and 'Convert.ToString(obj)' do exactly one thing.通过使用“逆向工程”( ilspy ),我发现“object.ToString()”和“Convert.ToString(obj)”只做一件事。 infact 'Convert.ToString(obj)' call 'object.ToString()' so 'object.ToString()' is faster.事实上 'Convert.ToString(obj)' 调用 'object.ToString()' 所以'object.ToString()' 更快。

Object.ToString Method : Object.ToString 方法

class System.Object
{
    public string ToString(IFormatProvider provider)
    {
        return Number.FormatInt32(this, null, NumberFormatInfo.GetInstance(provider));
    }
}

Conver.ToString Method : Conver.ToString 方法

class System.Convert
{
    public static string ToString(object value)
    {
        return value.ToString(CultureInfo.CurrentCulture);
    }
}

Convert.Tostring() function handles the NULL whereas the.ToString() method does not. Convert.Tostring() function 处理 NULL 而 .ToString() 方法不处理。 visit here .访问这里

In C# if you declare a string variable and if you don't assign any value to that variable, then by default that variable takes a null value.在 C# 中,如果您声明一个字符串变量并且您没有为该变量分配任何值,则默认情况下该变量采用 null 值。 In such a case, if you use the ToString() method then your program will throw the null reference exception.在这种情况下,如果您使用 ToString() 方法,那么您的程序将抛出 null 引用异常。 On the other hand, if you use the Convert.ToString() method then your program will not throw an exception.另一方面,如果您使用 Convert.ToString() 方法,那么您的程序将不会引发异常。

  • Convert.Tostring() basically just calls the following value == null? String.Empty: value.ToString() Convert.Tostring()基本上只是调用以下value == null? String.Empty: value.ToString() value == null? String.Empty: value.ToString()

  • (string)variable will only cast when there is an implicit or explicit operator on what you are casting (string)variable仅在您要转换的内容上有隐式显式运算符时才会转换

  • ToString() can be overriden by the type (it has control over what it does), if not it results in the name of the type ToString()可以被类型覆盖(它可以控制它的作用),如果不是,它会导致类型的名称

Obviously if an object is null , you can't access the instance member ToString() , it will cause an exception显然如果一个 object 是null ,你不能访问实例成员ToString() ,会导致异常

For nullable types ToString() actually handles null values:对于可为空类型ToString()实际上处理null值:

int? i = null;
        
var s1 = i.ToString();  // returns ""

var s2 = Convert.ToString(i);   // returns ""

Just to remedy the existing answers.只是为了补救现有的答案。

Source:来源:

https://docs.microsoft.com/en-us/dotnet/api/system.nullable-1.tostring?view=net-5.0 https://docs.microsoft.com/en-us/dotnet/api/system.nullable-1.tostring?view=net-5.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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