1

我收到一个 InvalidCastException 设置两个类型相等。对可能导致这种情况的特定行为的想法?

  • 使用字段定义定义 this.governanceTemplateList 不会更改异常。
  • 在构造函数中将 this.governanceTemplateList 定义为新的 ObservableCollection 会引发完全相同的异常。
  • 以下代码位于 WCF 服务库中,使用 .NET 4.0。

编辑器、异常、监视和参考的屏幕截图。

解决方案:

Daniel Hilgarth 是正确的,正是上面的代码行引发了异常。我将空值转换为可空值(DateTime?),但隐式转换无法转换空值。为了正确转换,您必须使用 AS 关键字。

governanceTemplateTimestamp = (DateTime?)dr["GovernanceTemplateTimestamp"]; //Invalid

governanceTemplateTimestamp = dr["GovernanceTemplateTimestamp"] as DateTime?; //Valid
4

1 回答 1

2

异常很可能发生在上面的行。被标记为有问题的行没有执行任何强制转换。
我想那GovernanceTemplateTimestampDBNull你的 DataRow 中。DBNull不能转换为DateTime?.

于 2012-12-10T15:21:46.983 回答