无法将对象参数强制转换为可为空的日期时间

本文关键字:时间 日期 转换 对象 参数 | 更新日期: 2023-09-27 18:28:17

var OverDate = new ObjectParameter("OverDate",(DateTime)DateTime.Now);
DateTime? convertedDate = (DateTime?) OverDate.Value;

它能够构建,但当我提供convertedDate作为类型 DateTime? 的输入参数时引发运行时异常

我可以知道转换的哪一部分是错误的,因为我得到以下异常

无法强制转换类型为"系统.数据.对象.对象参数"的对象 键入"系统可逆">

无法将对象参数强制转换为可为空的日期时间

使用

DateTime? convertedDate = OverDate.Value as DateTime?;

以下代码没有错误。 尝试使用以下代码创建新项目。 有时,当程序中发生异常并且您没有异常处理程序(try/catch(时,代码会跳过并给出令人困惑的错误消息。 项目中的某个位置可能有例外。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//add reference for System.Data.Entity
using System.Data.Objects;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var OverDate = new ObjectParameter("OverDate", (DateTime)DateTime.Now);
            DateTime? convertedDate = (DateTime?)OverDate.Value;
        }
    }
}
​