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
不客气。问题在于,你的推理方向与编译器原因相反。你在说:“我知道这是一种期待对象的东西”。但是编译器并不知道你*先验*希望选择“对象”方法。编译器试图以另一种方式推理。它问的是“期望对象与这个表达式兼容的方法吗?”要知道它必须问“表达式的类型是什么?” **问题是它无法计算出表达式的类型以决定表达式是否有效。** –