如何做的ToString一个可能为null的对象呢? [英] How to do ToString for a possibly null object?

查看:1589
本文介绍了如何做的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的对象呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆