Conditional operator in C# and return types [duplicate]

白昼怎懂夜的黑 提交于 2019-12-12 13:43:20

问题


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

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