如何用零填充可为空的整数? [英] How can I pad nullable ints with zeros?
问题描述
有什么方法可以像普通int一样填充可为null的int值?
Is there any way to pad nullable int with zeros the way you can with normal int?
myInt.ToString("D3")
似乎不适用于nullale整数,但是对于我当前的项目,我感觉我需要使用可为空的int
,以便在数组中获取null
值,而不是默认值0
the myInt.ToString("D3")
doesn't seem to work on nullale ints but for my current project I feel like I need to use nullable int
in order to get the null
value in my array instead of 0 as the default.
推荐答案
这是因为int?
实际上是Nullable<T>
,其中T
是int
.
That is because int?
is actually Nullable<T>
where T
is int
here.
调用ToString
将在Nullable
结构而不是int
上调用它. Nullable<T>
不了解int
具有的ToString
重载.
Calling ToString
will call that on the Nullable
struct, not the int
. Nullable<T>
has no knowledge of the overloads of ToString
which int
has.
您必须先获取整数值:
myInt.GetValueOrDefault(0).ToString("D3")
这篇关于如何用零填充可为空的整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!