可空的ToString() [英] Nullable ToString()

查看:280
本文介绍了可空的ToString()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我到处看到像小亭子:

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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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