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

Convert.ToString().ToString()有什么不同?

我在网上发现了很多不同,但是主要的不同是什么呢?

140504 次浏览

Convert.ToString()处理 null,而 ToString()不处理。

对对象调用 ToString()假定对象不为空(因为对象需要存在才能对其调用实例方法)。Convert.ToString(obj)不需要假定对象不为 null (因为它是 Convert 类上的静态方法) ,而是在 为 null 时返回 String.Empty

Convert.ToString()中,Convert 处理 NULL值或不处理 NULL值,但在 .ToString()中它不处理 NULL值和 NULL引用异常错误。因此,在良好的实践中使用 Convert.ToString()

让我们通过这个例子来理解其中的区别:

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

我们可以使用 i.ToString ()或者 Convert.ToString来转换整数 i。那么有什么区别呢?

它们之间的基本区别是 Convert函数处理 NULLS,而 i.ToString ()不处理; 它将抛出 NULL 引用异常错误。因此,作为良好的编码实践使用 convert始终是安全的。

对于代码爱好者来说,这是最好的答案。

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

您可以创建一个类并重写 toString方法来执行任何您想要的操作。

例如,您可以创建一个类 “我的邮箱”并覆盖 toString方法以发送电子邮件或执行其他操作,而不是编写当前对象。

Convert.toString将指定的值转换为其等效的字符串表示形式。

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

除了处理 null值的其他答案之外,Convert.ToString在调用基 Object.ToString之前尝试使用 IFormattableIConvertible接口。

例如:

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

结果:

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

ToString()不能处理 null 值,而 convert.ToString()可以处理 null 值,因此当您希望系统处理 null 值时,请使用 convert.ToString()

方法“基本上”是相同的,除了处理 无效

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

来自 MSDN:
方法

将指定的值转换为其等效的字符串表示形式。

Object.ToString

返回表示当前对象的字符串。

Convert.ToString(strName)将处理空值,而 strName.Tostring()将不处理空值并抛出异常。

因此,最好使用 Convert.ToString()而不是 .ToString();

ToString() Vs Convert.ToString()

相似之处:-

两者都用于将特定类型转换为 string,即 int 转换为 string、 float 转换为 string 或者将对象转换为 string。

区别:-

如果 Convert.ToString()将处理空值,则 ToString()不能处理空值。

例如:

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

我同意 @ < strong > Ryan 的回答。顺便说一下,从 C # 6.0开始,你可以使用:

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

或者

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

而不是

Convert.ToString(someString);

这里两种方法都用来转换字符串,但它们之间的基本区别是: Convert函数处理 NULL,而 i.ToString()不会抛出一个 NULL reference exception error.,所以使用 convert的良好编码实践总是安全的。

让我们看看例子:

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)首先尝试将 obj 转换为 我可转换,然后 IFormattable 格式化调用相应的 ToString(...)方法。如果参数值是 null,那么返回 string.Empty。作为最后的手段,返回 obj.ToString()如果没有其他工作。

值得注意的是,如果例如 value.ToString()返回 null,Convert.ToString(value) 可以返回 null

参见 。网络参考源

我写了这段代码并编译了它。

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

通过使用“逆向工程”(伊尔斯比) ,我发现“ object.toString ()”和“ Convert.toString (obj)”只做一件事。 事实上‘ Convert.ToString (obj)’调用‘ object.ToString ()’所以 < strong > ‘ object.ToString ()’更快。

ToString 方法 :

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

ToString 方法 :

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

函数处理 NULL,而.ToString ()方法不处理。访问 给你

在 C # 中,如果你声明了一个字符串变量,并且你没有给这个变量赋值,那么默认情况下这个变量会接受一个空值。在这种情况下,如果使用 ToString ()方法,那么程序将抛出空引用异常。另一方面,如果使用 Convert.ToString ()方法,则程序不会抛出异常。

  • Convert.Tostring()基本上只调用以下 value == null ? String.Empty: value.ToString()

  • 当有一个 含蓄露骨操作员在你正在铸造的时候,(string)variable将只有 演员

  • 根据类型,ToString()可以是 被覆盖了(它可以控制它所做的事情) ,如果不是,它会导致类型的名称

显然,如果一个对象是 无效,您就不能访问实例成员 ToString(),这将导致异常