为什么不能在此表达式中使用三元运算符? [英] Why can't I use a ternary operator with this expression?

查看:295
本文介绍了为什么不能在此表达式中使用三元运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);

我不明白为什么如果一个或另一个要进行隐式转换

I don't understand why there needs to be an implicit conversion if one or the other is going into a dictionary expecting type Object.

推荐答案

在C#中,每个条件表达式都必须具有一个类型。您的表达式是什么类型?

In C#, every conditional expression must have a type. What type is your expression of?

我理解您的担心,您的特殊情况不需要进行转换,但这是C#编译器的工作方式,因此您必须服从

I understand your concern, the conversion is not needed for your particular case, but this is how C# compiler works, so you have to obey its rules.

这应该起作用(我没有检查):

This should work instead (I didn't check though):

dict.Add("breakit", myDate.HasValue ? (object)myDate.Value : (object)DBNull.Value);

这篇关于为什么不能在此表达式中使用三元运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆