System.InvalidCastException:无法强制转换'System.Xml.XmlDocument类型的对象

时间:2013-02-27 16:21:41

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

我正在接受一些像这样的例外     tmo =(testobjectt)value [i];这是“无法将类型'System.Xml.XmlNode []'的对象强制转换为类型system.type”。

有关此问题的任何想法?唯一可用的解决方案是重新启动Windows服务,以便在UI中提供所有内容。另一件事是我们在客户端和服务器之间有API。

这是我正在使用的代码段:

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

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

1 个答案:

答案 0 :(得分:1)

我对此错误原因的最佳猜测是,您依赖于col ObjectArray中反序列化对象的顺序。这不能保证。

可能在简单表示中,您的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] 无法保证以匹配数组项的原始顺序。