三元条件和可为 null 的类型

发布于 2024-11-26 19:29:33 字数 850 浏览 4 评论 0原文

可能的重复:
为什么此代码在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

初心未许 2024-12-03 19:29:33

因为无法确定'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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文