当前位置: 移动技术网 > IT编程>开发语言>c# > 浅谈C#中ToString()和Convert.ToString()的区别

浅谈C#中ToString()和Convert.ToString()的区别

2019年07月18日  | 移动技术网IT编程  | 我要评论

浅谈tostring()和convert.tostring()方法的区别

一、一般用法说明

  tostring()是object的扩展方法,所以都有tostring()方法;而convert.tostring(param)(其中param参数的数据类型可以是各种基本数据类型,也可以是bool或object类对象。

二、tostring()和convert.tostring()的区别

  一般情况下,这两种方法都可以通用,但是当返回的数据类型中有可能出现null值时如果调用tostring方法了,就会返回nullreferenceexception,除非你要捕捉此异常再做处理,否则在这种情况下就应考虑使用convert.tostring()方法了,因为convert.tostring(null)不会抛出异常而是返回空字符串。
主要的区别就如上所示,由于tostring()是扩展方法,扩展自object,所以转null报异常。而convert.tostring()返回空字符串。

  不过convert.tostring(),作用不算太大,因为:

static void main(string[] args)
    {
      string str1 = "";
      console.writeline(convert.tostring(str1) == null); //false
      console.writeline(convert.tostring(str1) == "");  //true

      string str2 = null;
      console.writeline(convert.tostring(str2) == null); //true
      console.writeline(convert.tostring(str2) == "");  //false

      console.readkey();
    }

null转了之后还是null,""转了之后还是""。

  所以,配合上string.isnullorempty(convert.tostring())还是比较方便的。

    console.writeline(string.isnullorempty(convert.tostring(str1)));  //true
    console.writeline(string.isnullorempty(convert.tostring(str1)));  //true

   另外,如果是跟某字符串对比,那么使用convert.tostring()还是很方便的,例如

    if(convert.tostring(str) == "123")
    {

    }

三、object到string的转换

  从 object 到 string 大致有四种方式,包括显式转换和as关键词的使用:obj.tostring()、convert.tostring()、(string)obj、obj as string。他们都能将 object 对象转换成 string 对象。

  前两个方法通常是由别的对象得到 string 对象,它们间的区别如前文所述主要表现在:

tostring() :如果 obj 为 null,调用 obj.tostring() 方法会导致 nullreferenceexception 异常。

convert.tostring():如果 obj 为 null,调用 convert.tostring()会返回null

(string):用强制转换 (string)obj 要求 obj 的运行时类型必须是 string。如果不是,就会抛出异常。

as :用 as 方法则会相对平稳,当 obj 的运行时类型不是 string 时会返回 null 而不抛出异常。

  所以在通常在我们需要得到某个对象的 string 表达形式时,我们应该使用 tostring() 和 convert.tostring(),这时候你就得根据情形选一个,假如你能保证你的对象不为 null,则两个差不多。如果有可能为 null,你就应该用 convert.tostring(),如果你希望它为 null 的时候抛出异常,那么当然可以选择 tostring()。

  tostring()这个方法太方便了,以致于以为就它这一种方法, 一般都是转之前先判断是否为null.

以上所述是本文的全部内容,希望对大家有所帮助!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网