为什么的ToString()上的一个空字符串导致空的错误,当的ToString()与空值可为空INT工作正常? [英] Why does .ToString() on a null string cause a null error, when .ToString() works fine on a nullable int with null value?
问题描述
将selectedItem
有两个字段:
-
诠释? _cost
-
字符串_serialNumber
int? _cost
string _serialNumber
在这个例子中, _cost
和 _serialNumber
的将selectedItem
都是空。我读经由它们的属性将selectedItem
的领域,并与他们的价值观填写文本框,当...
In this example, _cost
and _serialNumber
of selectedItem
are BOTH null. I am reading through the fields of selectedItem
via their properties, and filling in textboxes with their values, when...
TextBox1.Text = selectedItem.Cost.ToString(); //no error
TextBox2.Text = selectedItem.SerialNumber.ToString(); //error
据我所知, SerialNumber.ToString()
是多余的(因为它已经是一个字符串),但我不明白为什么这会导致此异常:
I understand that SerialNumber.ToString()
is redundant (because it is already a string), but I don't understand why this causes this exception:
可空对象必须有一个值。
Nullable object must have a value.
-
诠释? _cost
可为空,并且不具有价值,但它不给我例外。 -
字符串_serialNumber
可为空,并且不具有价值,但它的确实给我例外。
int? _cost
is nullable, and does not have a value, yet it does not give me the exception.string _serialNumber
is nullable, and does not have a value, yet it does give me the exception.
这问题上倒是,那家伙基本上是问同样的事情,但有没有指定的答案,也没有解释为什么一个可空 INT
?例如,我可以使用的ToString()
上一个可空INT,但不是一个空字符串?
This question touches on it, the guy is essentially asking the same thing, but there is no designated answer, and it also doesn't explain why a nullable int
? For example, can I use .ToString()
on a nullable int but not on a null string?
推荐答案
由于字符串
类型的空
真的指向什么都没有,没有在内存中的任何对象。
但 INT?
输入(可为空),即使设置为空$值C $ C>仍然指向某个对象。
如果你读杰弗里里希特的通过C#CLR你会发现,可空类型是为了使工作与DB的常见类型有一些incapsulated逻辑只是外观类空更方便。
Because string
type's null
really points to nothing, there isn't any object in memory.
But int?
type(nullable) even with value set to null
still points to some object.
If you read Jeffrey Richter's "CLR via C#" you'll find out that nullable type are just facade classes for common types with some incapsulated logics in order to make work with DB null more convenient.
这篇关于为什么的ToString()上的一个空字符串导致空的错误,当的ToString()与空值可为空INT工作正常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!