[英]How to handle null exception when converting from object to string?
Just curious: 只是好奇:
These lines throw Invalid Cast Exception
: Unable to cast object of type 'System.Double' to type 'System.String'.
这些行抛出
Invalid Cast Exception
: Unable to cast object of type 'System.Double' to type 'System.String'.
Invalid Cast Exception
Unable to cast object of type 'System.Double' to type 'System.String'.
Object obj = new object();
obj = 20.09089;
string value = (string)obj;
I receive the obj
value from a library
. 我从
library
收到obj
值。
How to simply convert to string
when we don't know the type of object
while enumerating? 当我们在枚举时不知道
object
的类型时,如何简单地转换为string
?
这就是为什么.net中的每个对象都具有ToString()方法(从Object继承)的原因
string str = (obj == null) ? string.Empty : obj.ToString();
This is an boxing / unboxing issue. 这是装箱/拆箱的问题。
20.09089
is a double
by default. 默认情况下,
20.09089
是double
20.09089
。 When you wanna unbox a primitive type from object
, you need to unbox it the original type first . 要从
object
取消原始类型的装箱时,需要首先将其原始类型取消装箱。
Object obj = new object();
obj = 20.09089;
string value = ((double)obj).ToString();
or simplify; 或简化
Object obj = new object();
obj = 20.09089;
string value = obj.ToString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.