为什么以下失败/"从'Int64'到'DateTime'的无效转换." 例外?
long oldDate=new DateTime(2015, 1, 1).Ticks;
DateTime newDate=Convert.ToDateTime(oldDate);
Run Code Online (Sandbox Code Playgroud)
.Ticks是long/Int64,Convert.ToDateTime(Int64)MSDN文档显示接受long/Int64的方法.
public static DateTime ToDateTime(
long value
)
Run Code Online (Sandbox Code Playgroud)
编辑:正如下面的ebyrob指出它应该是:
long oldDate=new DateTime(2015, 1, 1).Ticks;
DateTime newDate=new DateTime(oldDate);
Run Code Online (Sandbox Code Playgroud)
从MSDN文档Convert.ToDateTime Method (Int64):
调用此方法始终会抛出InvalidCastException.
和
返回值类型:System.DateTime不支持此转换.没有返回任何值.
来源:http://msdn.microsoft.com/en-us/library/400f25sk.aspx(该链接指向.NET 4.5文档,但对于低至2.0的所有版本都是如此).
我不确定为什么不支持这一点,特别是如果new DateTime(oldDate)运作良好:
DateTime newDate = new DateTime(oldDate);
Run Code Online (Sandbox Code Playgroud)