var dict = new Dictionary<string, object>();
DateTime? myDate;
/*Next line gives: Type of conditional expression cannot be
determined because there is no implicit conversion between 'System.DateTime?'
and 'System.DBNull' */
dict.Add("breakit", myDate.HasValue ? myDate.Value : DBNull.Value);
我不明白爲什麼需要有一個隱式轉換,如果其中一個要進入期望類型爲Object的字典。爲什麼我不能用這個表達式使用三元運算符?
這是一個非常常見的問題上左右。有關詳細信息,請參閱http://stackoverflow.com/questions/2215745/conditional-operator-cannot-cast-implicitly/2215959#2215959。另見我的相關文章http://blogs.msdn.com/b/ericlippert/archive/2010/05/27/cast-operators-do-not-obey-the-distributive-law.aspx –
@Eric我會一探究竟。謝謝! – scottm
不客氣。問題在於,你的推理方向與編譯器原因相反。你在說:「我知道這是一種期待對象的東西」。但是編譯器並不知道你*先驗*希望選擇「對象」方法。編譯器試圖以另一種方式推理。它問的是「期望對象與這個表達式兼容的方法嗎?」要知道它必須問「表達式的類型是什麼?」 **問題是它無法計算出表達式的類型以決定表達式是否有效。** –