問題描述
selectedItem
有兩個字段:
int?_成本
string _serialNumber
在這個例子中,selectedItem
的 _cost
和 _serialNumber
都為 null.我正在通過它們的屬性閱讀 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:
可空對象必須有值.
int?_cost
可以為空,并且沒有值,但它沒有給我例外.string _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.
這個問題觸及它,這家伙本質上在問同樣的事情,但有沒有指定的答案,它也沒有解釋為什么可以為 null int
?例如,我可以在可空 int 上使用 .ToString()
而不是在空字符串上使用嗎?
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?
推薦答案
因為 string
類型的 null
真的指向空,所以內存中沒有任何對象.
但是 int?
type(nullable) 即使將值設置為 null
仍然指向某個對象.
如果您閱讀 Jeffrey Richter 的CLR via C#"你會發現可空類型只是普通類型的外觀類,帶有一些封裝的邏輯,以便更方便地使用 DB null.
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.
查看 msdn 以了解可空類型.
Check msdn to learn about nullable types.
這篇關于為什么 .ToString() 在空字符串上導致空錯誤,當 .ToString() 在具有空值的可空整數上正常工作時?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!