问题
Possible Duplicates:
Why does null need an explicit type cast here?
Nullable types and the ternary operator. Why won't this work?
Attempting to do the following:
sqlCmd.Parameters.Add("@DateCreated", System.Data.SqlDbType.DateTime).Value
= myObject.DateCreated == DateTime.MinValue
? DBNull.Value : myObject.DateCreated;
I am getting this error:
Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DBNull' and 'System.DateTime'
I obviously understand the error but why does type even matter given that Parameters.Value is of type object? Is there a way to accomplish what I am trying to do?
回答1:
It doesn't make a difference that the return value is going into something that is an object, because the type of the return value has to be determined first.
Cast one of the two values (DBNull.Value, myObject.DateCreated) to a base of the other and you 'll be fine. In this case, the base can even be object.
回答2:
This is an extremely frequently asked question. See my answer to this question:
Conditional operator cannot cast implicitly?
This article from my blog describes a related scenario that also causes user confusion:
http://blogs.msdn.com/b/ericlippert/archive/2010/05/27/cast-operators-do-not-obey-the-distributive-law.aspx
来源:https://stackoverflow.com/questions/5386251/conditional-operator-in-c-sharp-and-return-types