gpt4 book ai didi

c# - 可为空的 ToString()

转载 作者:IT王子 更新时间:2023-10-29 03:32:39 24 4
gpt4 key购买 nike

我到处都看到这样的结构:

int? myVar = null;
string test = myVar.HasValue ? myVar.Value.ToString() : string.Empty;

为什么不简单地使用:

string test = myVar.ToString();

这不完全一样吗?至少 Reflector 是这样说的:

public override string ToString()
{
if (!this.HasValue)
{
return "";
}
return this.value.ToString();
}

那么,这是正确的(较短的版本)还是我遗漏了什么?

最佳答案

你说得很对。也在 this question ,建议使用前一种解决方案,但实际上没有人注意到 ToString() 已经给出了正确答案。

也许更冗长的解决方案的论据是可读性:当您调用 ToString() 时,应该null,您通常期望一个NullReferenceException,尽管这里并没有抛出它。

关于c# - 可为空的 ToString(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2449008/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com