可能重複:
C# okay with comparing value types to null爲什麼要在C#中將結構與NULL合法比較?
考慮與時間跨度,這是一個結構下面的代碼:
// will not compile - illegal
TimeSpan ts = null;
但是,下面的代碼不會編譯和合法,儘管表達總是假的:
if (ts == null)
Console.WriteLine("this line will never be hit");
有人可以告訴我爲什麼將結構設置爲NULL是無效的,但可以將它與一個結果比較嗎?
http://stackoverflow.com/questions/2022425/comparing-structs-to-null,http://stackoverflow.com/questions/648115/how-can-an-object-not-be-比較爲null,http://stackoverflow.com/questions/1225949/why-can-timespan-and-guid-structs-be-compared-to-null,http://stackoverflow.com/questions/1972262/ c-sharp-okay-with-comparison-value-types-null- – nawfal 2012-04-09 23:44:31
如果無法將結構與null進行比較,那麼將如何處理Nullable? –
2012-04-09 23:46:19
@AnthonyPegram:更好的問題是;你將如何實現'Nullable'作爲'struct'? (當然,你不能)。 'Nullable ''當然可以作爲參考類型來實現 –
2012-04-10 00:02:06