简体   繁体   English

从对象转换为字符串时如何处理空异常?

[英]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 ExceptionUnable 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.09089double 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.

相关问题 在何处/如何实例化对象以处理空引用异常 - Where/How to instaniate an object to handle null reference exception 使用其他类的GetEnumerator时如何处理foreach空异常? - How to handle foreach null exception when using GetEnumerator from other class? 处理转换为字符串时处理Convert.ToBase64String内存不足异常 - Handle Convert.ToBase64String out of memory exception when converting to string 如何处理HtmlDocument空异常 - How to handle HtmlDocument null exception 如何处理从 webgrid 中的控制器返回的列值的空异常? - How to handle null exception for column values returned from controller in webgrid? Any() 当对象为空时抛出异常,如何返回空? - Any() Throw Exception when object is null, how return null instead? 从Base-64字符串转换为图像时出现异常 - Exception when converting to image from Base-64 string 如果model为null,如何处理null异常,如何在mvc中的视图中处理它? - how to handle null exception if model is null , how to handle it in view in mvc? 当为类值对象重载operator +时如何处理null? - How to handle null when overloading operator + for a class value object? 使用 String.StartsWith 方法时如何处理 NULL - How to handle NULL when using String.StartsWith method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM