簡體   English   中英

為什么字符串屬性上的GetType會導致NullReferenceException?

[英]Why does a GetType on a string-property result in a NullReferenceException?

當我在int-或DateTime屬性上調用GetType時,我得到了預期的結果,但是在字符串屬性上,我得到一個NullReferenceException(?):

private int      PropInt    { get; set; }
private DateTime PropDate   { get; set; }
private string   propString { get; set; }

WriteLine(PropInt.GetType().ToString());    // Result : System.Int32
WriteLine(PropDate.GetType().ToString());   // Result : System.DateTime
WriteLine(propString.GetType().ToString()); // Result : NullReferenceException (?!)

有人可以解釋一下怎么來? 字符串支柱與int-prop的區別是什么?

如果屬性的值為null ,那么在嘗試訪問對象方法或屬性(如GetType()時,您將獲得NullReferenceException。 intDateTime這樣的原始類型是值類型,因此不能保存null值,這就是GetType()不會失敗的原因,而不是任何其他成員函數。

因為string是引用類型,而其他不是。 默認情況下,DateTime和Int必須具有值,它們不能為空。

你必須要了解的是編譯器正在為你創建一個存儲信息的變量。 在C#3.0中,您不必顯式聲明它,但它仍然存在,因此它創建一個DateTime變量和一個int變量並將它們初始化為默認值,以免引起編譯器錯誤。 使用字符串,它不需要執行此操作(初始化默認值),因為它是引用類型。

要強調其他答案所指示的內容,請將int更改為int? 和DateTime到DateTime? 並嘗試再次運行代碼。 由於這些值現在可以保存空值,因此您將獲得相同的異常。

propString的初始值為null。 我們不能執行null方法。 如果你初始化propString:propString =“”那么你可以執行沒有Exception的GetType()

代碼無例外:

private int      PropInt    { get; set; }
private DateTime PropDate   { get; set; }
private string   propString { get; set; }

propString = ""; // propString != null

WriteLine(PropInt.GetType().ToString());    // Result : System.Int32
WriteLine(PropDate.GetType().ToString());   // Result : System.DateTime
WriteLine(propString.GetType().ToString()); // Result : System.String

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM