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

2023-09-02 23:49:20 作者:他似梦别当真

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

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

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

 的String =+ MyObj中;
 

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

解决方案

 的String =(MyObj中的String.Empty ??)的ToString();
 
Print打印自动调用对象的toSrting方法

 的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}";

 
精彩推荐
图片推荐