Convert和Parse对null值处理的区别

类型的转换在日常的变成中是经常被用到的,我们最常用的类型转换的方法就是Convert和Parse,

下面来说一下这两者null值处理的区别。

            int i1 = Convert.ToInt32(null);//i1=0
            int i2 = Int32.Parse(null);//throw an expection:Value cannot be null.

由此可见,Convert对null值是有容错的,如果是null则返回0,而Parse没有做容错,会抛出异常。

多说一句。

            object obj = null;
            string str1 = obj.ToString();//throw an expection:Object reference not set to an instance of an object.
            string str2 = (string)null;//str2 = null

获取object的ToString时,最好用string强转。

 

 

 

posted @ 2013-11-01 15:39  jiangfei5945  阅读(392)  评论(0编辑  收藏  举报