我一直在使用 Visual Studio 2010,C#。
我已经为这个项目工作了近一年了。在其中,我使用存储在单独的 XML 文件中的信息来构建图像。这个过程对我来说已经成功了数百次,没有任何问题。
我已迁移到新机器。之前的机器是32位的,新的机器是64位的。当我打开文件并尝试反序列化时,会引发以下异常:
System.InvalidCastException was unhandled Message=[A]System.Collections.Generic.List
1[BookCreator.pageFontInfo] cannot be cast to [B]System.Collections.Generic.List
1[BookCreator.pageFontInfo]. Type A originates from 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' in the context 'LoadNeither' at location 'C:\Windows\Microsoft.Net\assembly\GAC_64\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll'. Type B originates from 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' in the context 'LoadNeither' at location 'C:\Windows\Microsoft.Net\assembly\GAC_64\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll'.
这是生成错误的代码:
List<pageFontInfo> info;
XmlSerializer serializer = new XmlSerializer(typeof(List<pageFontInfo>));
TextReader tr = new StreamReader(openFile);
info = (List<pageFontInfo>)serializer.Deserialize(tr); <---error thrown
pageFontInfo 是自定义构建的可序列化结构。它包含两个字符串、一个 float 和一个点列表。我不知道出了什么问题。我比较了列表的两个“起源”,它们是相同的。我完全被难住了。在迁移之前,这已经成功了数百次。
编辑: 我刚刚检查过。我已在另一台 64 位计算机上运行编译后的 .exe 和源代码。所以现在发生的任何问题都与此无关。它特定于此 Visual Studio 2010 安装。
最佳答案
找到了!我开始单步调试我的代码,发现两个相同的程序集实际上是不同的实例。我一直将该程序用作网站的类库。因此,工作目录中包含项目的 .dll 以及开始调试过程时创建的 .exe。
加载时,程序同时加载 .dll 和 .exe。我所要做的就是进入工作目录,并将它们都删除。然后错误就消失了。
关于c# - 在新机器上安装后抛出 InvalidCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6811855/