sco*_*ttm 5 c# ternary-operator implicit-conversion
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);
Run Code Online (Sandbox Code Playgroud)
我不明白为什么如果一个或另一个进入期望类型为Object的字典,则需要进行隐式转换.
在C#中,每个条件表达式都必须具有类型.你的表达是什么类型的?
我理解您的担忧,您的特定情况不需要转换,但这是C#编译器的工作方式,因此您必须遵守其规则.
这应该工作(我没有检查):
dict.Add("breakit", myDate.HasValue ? (object)myDate.Value : (object)DBNull.Value);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3388 次 |
| 最近记录: |