问题
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