【问题标题】:System.InvalidCastException: Unable to cast object of type 'System.Xml.XmlDocumentSystem.InvalidCastException:无法转换类型为“System.Xml.XmlDocument”的对象
【发布时间】:2013-02-27 16:21:41
【问题描述】:

我遇到了一些奇怪的异常,例如 tmo = (testobjectt)value[i];这是“无法将'System.Xml.XmlNode []'类型的对象转换为system.type类型”。

关于这个问题有什么想法吗?唯一可用的解决方案是重新启动 Windows 服务,以便 UI 中的所有内容都可用。另一件事是我们在客户端和服务器之间确实有 API。

这是我正在使用的代码 sn-p:

public class Testarray: ArrayList

     // Release resources
     if (rd != null)
     {
        rd.Close();
     }

     return retval;
  }


Assembly a = Assembly.GetAssembly(typeof(Testobject));
                  string myType = a.gettype;
                  string xml = xmlvalue;
DataModelObject dmo;
// Deserialize and process the object
                  Testarraycol = Testarray.Deserialize(xml, Type.type);
tmo= (Testobject)value[i];  // this is where the exception occurs

更新 是否有任何地方需要无参数构造,我正在手动检查整个项目在序列化时丢失的任何地方?

【问题讨论】:

  • 你能发布ObjectArray.Deserialize方法吗?
  • @Alex Filipovici 我用反序列化方法编辑了我的问题
  • 你到底为什么要使用ArrayListXmlTextReader?自 .NET 2.0 以来,它们都已被弃用!
  • @John Saunders 您是在谈论这里将面临的任何性能问题,还是只是一些升级级别的变化?那么这是最好的选择
  • XmlReader.Create()代替new XmlTextReader(),用List<T>代替ArrayList

标签: c# .net visual-studio-2010 .net-4.0


【解决方案1】:

我对这个错误的最佳猜测是你依赖于colObjectArray 中反序列化对象的顺序。这不能保证。

您的ObjectArray.Deserialize 方法可能如下所示:

public static ObjectArray Deserialize(string xml, Type type)
{
    var s = new XmlSerializer(typeof(ObjectArray),
        new Type[] { type });
    var o = (ObjectArray)s.Deserialize(new StringReader(xml));
    return o;
}

但这意味着序列化的xml 中不属于Type type(方法的参数)的任何其他对象,都将被反序列化为System.Xml.XmlNode[]

可能是在col[i] 实际持有ViewObjectInfo 时发生错误。

如果您想确保这两种类型都被正确反序列化,请使用类似于以下内容:

public static ObjectArray Deserialize(string xml, Type[] types)
{
    var s = new XmlSerializer(typeof(ObjectArray), types);
    var o = (ObjectArray)s.Deserialize(new StringReader(xml));
    return o;
}

然后这样称呼它:

ObjectArray col = ObjectArray.Deserialize(xml, 
    new Type[] { typeof(DataModelObject), typeof(ViewObjectInfo) }
    );
dmo = (DataModelObject)col.OfType<DataModelObject>().Skip(i).First();

无论如何,如果你只需要反序列化DataModelObject对象并保持你当前的逻辑,你只需要替换:

dmo = (DataModelObject)col[i];

dmo = (DataModelObject)col.OfType<DataModelObject>().Skip(i).First();

不要忘记,col[i]不保证与数组项的原始顺序匹配。

【讨论】:

  • 您是否检查过此集合中是否有任何项目col.OfType&lt;DataModelObject&gt;()?也许你应该考虑重写你的Deserialize 方法。
  • 我什至使用了 FirstOrDefault() 而不是 First(),然后将“dmo”设为 null
  • 能否也发布一个 XML 示例?
  • 重现这个问题非常困难,我需要将我的系统置于待机模式并等待一天然后启动,这几天我有很多工作,我会发布xml一次
  • 不,很可能不会有任何区别:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-18
  • 2020-04-16
  • 2020-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多