问题描述
我到处看到像小亭子:
int? myVar = null;
string test = myVar.HasValue ? myVar.Value.ToString() : string.Empty;
为什么不能简单地用:
Why not use simply:
string test = myVar.ToString();
是不是完全一样?
至少反射说:
Isn't that exactly the same ?At least Reflector says that:
public override string ToString()
{
if (!this.HasValue)
{
return "";
}
return this.value.ToString();
}
那么,这是否正确(短版)还是我失去了一些东西?
So, is that correct (the shorter version) or am I missing something?
推荐答案
您是相当正确的。此外,在,前者的解决方案建议,而没有人真正启事 。的ToString()
已经给出了正确的答案
You are quite correct. Also in this question, the former solution is suggested while nobody actually notices ToString()
already gives the correct answer.
也许对于更详细的解决方案的说法是可读性:当你调用的ToString()
的东西,是的应该的是空
,你平时的期望的一个的NullReferenceException
,虽然这里没有抛出。
Maybe the argument for the more verbose solution is readability: When you call ToString()
on something that is supposed to be null
, you usually expect a NullReferenceException
, although here it isn't thrown.
这篇关于可空的ToString()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!