Why can't I use a ternary operator with this expression? [duplicate]

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-10 13:52:58

问题


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.


回答1:


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

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



回答2:


Did you try:

DateTime? date = myDate.HasValue ? myDate.Value : null;

dict.Add("breakit", date);


来源:https://stackoverflow.com/questions/6507715/why-cant-i-use-a-ternary-operator-with-this-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!