Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/275.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 有效的ObservableCollection强制转换引发InvalidCastException_C#_.net_Wcf - Fatal编程技术网

C# 有效的ObservableCollection强制转换引发InvalidCastException

C# 有效的ObservableCollection强制转换引发InvalidCastException,c#,.net,wcf,C#,.net,Wcf,我收到一个InvalidCastException,因为它将两种类型设置为彼此相等。关于可能导致这种情况的特定行为的想法 使用字段定义定义this.governanceTemplateList不会更改异常 将this.governanceTemplateList定义为构造函数中的新ObservableCollection会引发完全相同的异常 以下代码位于WCF服务库中,使用.NET 4.0 解决方案: Daniel Hilgarth是正确的,正是上面的代码行引发了异常。我将空值转换为可空值

我收到一个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

例外情况很可能发生在上面这行。标记为违规行的行未执行任何强制转换。

我猜
GovernanceTemplateTimestamp
在您的数据行中是
DBNull
DBNull
不能强制转换为
DateTime?

显示一些代码。如果您在运行时遇到无效的强制转换异常,则无法将对象中的内容强制转换为您要将其强制转换为的内容,例如,以下情况将导致它
object o=“word”
inti=(int)o所有相关代码都显示在带有屏幕截图的链接中。