问题描述
是否有一种简单的方法可以执行以下操作:
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;
如果 Convert.ToString() 对此有适当的重载,那就太好了.
It would be great if Convert.ToString() had a proper overload for this.
推荐答案
C# 6.0
使用 C# 6.0,我们现在可以拥有原始方法的简洁、免转换版本:
With C# 6.0 we can now have a succinct, cast-free version of the orignal method:
string s = myObj?.ToString() ?? "";
甚至使用插值:
string s = $"{myObj}";
原答案:
string s = (myObj ?? String.Empty).ToString();
或
string s = (myObjc ?? "").ToString()
更简洁.
不幸的是,正如已经指出的那样,您通常需要在任一侧进行强制转换才能使其与非 String 或 Object 类型一起使用:
Unfortunately, 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()
因此,虽然看起来很优雅,但演员阵容几乎总是必要的,而且在实践中并不那么简洁.
Therefore, while it maybe appears elegant, the cast is almost always necessary and is not that succinct in practice.
正如其他地方所建议的,我建议使用扩展方法来使这个更简洁:
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();
}
这篇关于如何为可能为空的对象执行 ToString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!