日期:2014-05-20  浏览次数:20768 次

高手进来解释下 as string和toString
我调试时看到
当值为null时,我知道tostring会抛出异常,而as string不会,但里面有值时,会显示出来!例如text上面会显示"15"
this.txtRoomRate.Text = this.dataGridView1.Rows[0].Cells[5].Value.ToString();


当值为null时不会抛异常,有里面有值时,而值没有显示出来,这里面赋给text的值为""或null; 
this.txtRoomRate.Text = this.dataGridView1.Rows[0].Cells[5].Value as string; 

我想不通的是 as string强转后值在哪去了?

this.dataGridView1.Rows[0].Cells[5].Value 这里面的值是整型;

------解决方案--------------------
string.isnullorempty
检查对象类型的兼容性,并返回结果,如果不兼容就返回null; 

------解决方案--------------------
http://topic.csdn.net/t/20061101/17/5125826.html

as运算符

s运算符用于执行引用类型的显式类型转换。如果要转换的类型与指定的类型兼容,转换就会成功进行;如果类型不兼容,as运算符就会返回值null。

this.dataGridView1.Rows[0].Cells[5].Value 这里面的值是整型;

整型和string不兼容,返回的是null,就是this.txtRoomRate.Text值是空的。当然不显示。

在你toString()之前做个是否为空的判断就好了。

------解决方案--------------------
as 相当于 (string)this.dataGridView1.Rows[0].Cells[5].Value, 是数值的话,当然不行。
------解决方案--------------------
探讨
string.isnullorempty
检查对象类型的兼容性,并返回结果,如果不兼容就返回null;

------解决方案--------------------
expression as type
是显示强制类型转换,如果是实际类型不是指定类型的话不会抛出异常而返回null。
类似:
expression is type ? (type)expression : (type)null


------解决方案--------------------
toStirng() 是将值转换string型的
as String 是转换为string对象,相当于 as Button···
------解决方案--------------------
C# code
o as string //当o是一个string时返回o,否则为null
o.ToString()//调用o的一个ToString的方法

------解决方案--------------------
楼主用这个吧
Convert.ToString(i);
这个不抛异常

------解决方案--------------------
toStirng() 是将值转换string型的
as String 是转换为string对象
------解决方案--------------------
toStirng() 是将值转换string型的
as String 是转换为string对象,相当于 as Button···