【发布时间】:2022-06-28 22:48:45
【问题描述】:
MS 文档:
ToDateTime(对象)
将指定对象的值转换为 DateTime 对象。
ToDateTime(双)
调用此方法总是抛出 InvalidCastException。
ToDateTime(Int32)
调用此方法总是抛出 InvalidCastException。
ToDateTime(Int16)
调用此方法总是抛出 InvalidCastException。
ToDateTime(Int64)
调用此方法总是抛出 InvalidCastException。
ToDateTime(十进制) 调用此方法总是抛出 InvalidCastException。
为什么要提供这样的方法?
MS 源代码(包括 cmets):
https://referencesource.microsoft.com/#mscorlib/system/convert.cs
开头是一个矩阵,描述了支持哪些转换,哪些不支持:
// From: To: Bol Chr SBy Byt I16 U16 I32 U32 I64 U64 Sgl Dbl Dec Dat Str
// ----------------------------------------------------------------------
// Boolean x x x x x x x x x x x x x
// Char x x x x x x x x x x
// SByte x x x x x x x x x x x x x x
// Byte x x x x x x x x x x x x x x
// Int16 x x x x x x x x x x x x x x
// UInt16 x x x x x x x x x x x x x x
// Int32 x x x x x x x x x x x x x x
// UInt32 x x x x x x x x x x x x x x
// Int64 x x x x x x x x x x x x x x
// UInt64 x x x x x x x x x x x x x x
// Single x x x x x x x x x x x x x
// Double x x x x x x x x x x x x x
// Decimal x x x x x x x x x x x x x
// DateTime x x
// String x x x x x x x x x x x x x x x
// ----------------------------------------------------------------------
每个“x”代表支持的转换。但是对于空白“”(不支持的版本)也有方法,例如
public static DateTime ToDateTime(byte value) {
return ((IConvertible)value).ToDateTime(null);
}
另见类似问题: Why does System.Convert has ToDateTime that accepts DateTime?
【问题讨论】: