三元条件和可为 null 的类型
可能的重复:
为什么此代码在 C# 中无效?
请您分析一下 CS1 和CS2。为什么我需要在 CS1 中添加 (DateTime?)null
而在 CS2 中使用 _my_date = null;
。如果我不在 CS1 中添加 (DateTime?)
,我将受到以下错误的“祝福”:( 无法确定条件表达式的类型,因为没有......
DateTime? _my_date;
DataTable _dt = GetData();
// Code Snippet 1: CS1
_my_date = _dt.Rows[0]["MyDate"] == DBNull.Value ? (DateTime?)null : Convert.ToDateTime(_dt.Rows[0]["MyDate"]);
// Code Snippet 2: CS2
if (_dt.Rows[0]["MyDate"] == DBNull.Value)
{
_my_date = null;
}
else
{
_my_date = Convert.ToDateTime(_dt.Rows[0]["MyDate"]);
}
Possible Duplicate:
Why is this code invalid in C#?
Could you please analyze CS1 and CS2. Why should I need to add (DateTime?)null
in CS1 while I use _my_date = null;
in CS2. If I do not add (DateTime?)
in CS1, I will be 'blessed' :( by the following error
Type of conditional expression cannot be determined because there is no....
DateTime? _my_date;
DataTable _dt = GetData();
// Code Snippet 1: CS1
_my_date = _dt.Rows[0]["MyDate"] == DBNull.Value ? (DateTime?)null : Convert.ToDateTime(_dt.Rows[0]["MyDate"]);
// Code Snippet 2: CS2
if (_dt.Rows[0]["MyDate"] == DBNull.Value)
{
_my_date = null;
}
else
{
_my_date = Convert.ToDateTime(_dt.Rows[0]["MyDate"]);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为无法确定'null'的类型。我想这与类型的大小有关。例如,假设 null 表示所有位都将设置为 0(我在这里推测),那么您需要知道结构中有多少位。例如,short 的字节数比 DateTime 少。
因此,在这种情况下,您需要告知它所需的类型,因为它无法将 null 转换为可为 null 的日期时间。
Because the type of 'null' can not be determined. I imagine it's something to do with the size of types. Say for example that null, means all the bits will be set to 0 (I'm speculating here), then you need to know how many bits are in your structure. A short for example has less bytes than a DateTime.
So in this case you need to inform it as to the type it's expecting because it can't convert null, to the nullable datetime.