如何做的ToString一个可能为null的对象呢?

编程入门 行业动态 更新时间:2024-10-27 12:29:00
本文介绍了如何做的ToString一个可能为null的对象呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否有这样做下面的一个简单的方法:

的String = MyObj中== NULL? :myObj.ToString();

我知道我能做到以下几点,但我真的认为这是一个黑客:

的String =+ MyObj中;

这将是巨大的,如果Convert.ToString()有一个适当的重载这一点。

解决方案

的String =(MyObj中的String.Empty ??)的ToString();

的String =(myObjc ??)的ToString()

要更加简洁。

编辑:正如已经指出的那样,你会经常需要一个投两侧,使这项工作与非字符串或对象类型:

的String =(myObjc ??(对象))。的ToString() 字符串s =((对象)myObjc ??)的ToString()

编辑:

我不断收到了-票这个答案,但我想说,虽然它也许看起来高贵典雅,中投几乎总是必要的,因此不是简洁的做法,并可能更难阅读比其他几个答案。

至于其他地方的建议,我建议也许使用扩展方法,使这一清洁:

公共静态字符串ToStringNullSafe(该对象的值) {     回报(价值??的String.Empty)的ToString(); }

C#6.0编辑:

使用C#6.0,我们现在可以有上述方法的简洁,铸免费版本:

字符串s = MyObj中?的ToString()? ;

甚至

字符串s = ${} MyObj中;

Is there a simple way of doing the following:

String s = myObj == null ? "" : myObj.ToString();

I know I can do the following, but I really consider it as a hack:

String s = "" + myObj;

It would be great if Convert.ToString() had a proper overload for this.

解决方案

String s = (myObj ?? String.Empty).ToString();

or

String s = (myObjc ?? "").ToString()

to be even more concise.

Edit: As has been pointed out you'll often need a cast on either side to make this work with non String or Object types:

String s = (myObjc ?? (Object)"").ToString() String s = ((Object)myObjc ?? "").ToString()

Edit:

I keep receiving up-votes for this answer, but I would like to say that while it maybe appears elegant, the cast is almost always necessary and therefore is not that succinct in practice, and possibly harder to read than several other answers.

As suggested elsewhere, I recommend maybe using an extension method to make this cleaner:

public static string ToStringNullSafe(this object value) { return (value ?? string.Empty).ToString(); }

C# 6.0 Edit:

With C# 6.0 we can now have a succinct, cast-free version of the above method:

string s = myObj?.ToString() ?? "";

Or even:

string s = $"{myObj}";

更多推荐

如何做的ToString一个可能为null的对象呢?

本文发布于:2023-10-22 22:14:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1518881.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:能为   如何做   对象   ToString   null

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!