在C#和返回类型条件运算 [英] Conditional operator in C# and return types

查看:151
本文介绍了在C#和返回类型条件运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能显示的文件:结果
为什么空需要在这里投了明确的类型?结果
可空类型和三元运营商。 ?为什么不这项工作

试图做到以下几点:

sqlCmd.Parameters.Add("@DateCreated", System.Data.SqlDbType.DateTime).Value 
    = myObject.DateCreated == DateTime.MinValue 
    ? DBNull.Value : myObject.DateCreated;



我得到这个错误:

I am getting this error:

条件表达式类型
,因为有
间'System.DBNull'和'System.DateTime的

Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DBNull' and 'System.DateTime'

我明明知道错误,但为什么连型此事鉴于Parameters.Value是类型的对象?有没有办法来完成我所试图做的?

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?

推荐答案

它不会有所作为,返回值是进入东西是一个对象,因为的返回值的类型必须首先确定

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.

铸两个值( DBNull.Value myObject.DateCreated )为基其他,你会没事的。在这种情况下,碱可以甚至是物体

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.

这篇关于在C#和返回类型条件运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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