使用c# . net 2.0,我有一个组合数据类,它确实有[Serializable]属性。我正在创建一个XMLSerializer类并将其传递到构造函数中:

XmlSerializer serializer = new XmlSerializer(typeof(DataClass));

我得到一个异常说:

有错误反射类型。

在数据类内部有另一个复合对象。这是否也需要有[Serializable]属性,或者通过将它放在顶部对象上,它是否递归地应用到内部的所有对象?


当前回答

我最近在添加一个新属性时在一个web引用部分类中得到了这个。自动生成的类添加了以下属性。

    [System.Xml.Serialization.XmlElementAttribute(Order = XX)]

我需要添加一个类似的属性,其顺序比自动生成序列中的最后一个高,这为我修复了它。

其他回答

我发现. net 2.0中的Dictionary类不能使用XML进行序列化,但是在使用二进制序列化时可以很好地进行序列化。

我在这附近找了份工作。

有一种情况是连续的两个元素的顺序是相同的

[System.Xml.Serialization.XmlElementAttribute(IsNullable = true, Order = 0, ElementName = "SeriousInjuryFlag")]

.... 一些代码…

[System.Xml.Serialization.XmlElementAttribute(IsNullable = true, Order = 0, ElementName = "AccidentFlag")]

当我将代码更改为类中每个新Property的顺序加1时,错误就消失了。

我也认为Serializable属性必须在对象上,但除非我是一个完全的新手(我在一个深夜的编码会话中),以下工作来自SnippetCompiler:

using System;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using System.Xml.Serialization;

public class Inner
{
    private string _AnotherStringProperty;
    public string AnotherStringProperty 
    { 
      get { return _AnotherStringProperty; } 
      set { _AnotherStringProperty = value; } 
    }
}

public class DataClass
{
    private string _StringProperty;
    public string StringProperty 
    { 
       get { return _StringProperty; } 
       set{ _StringProperty = value; } 
    }

    private Inner _InnerObject;
    public Inner InnerObject 
    { 
       get { return _InnerObject; } 
       set { _InnerObject = value; } 
    }
}

public class MyClass
{

    public static void Main()
    {
        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(DataClass));
            TextWriter writer = new StreamWriter(@"c:\tmp\dataClass.xml");
            DataClass clazz = new DataClass();
            Inner inner = new Inner();
            inner.AnotherStringProperty = "Foo2";
            clazz.InnerObject = inner;
            clazz.StringProperty = "foo";
            serializer.Serialize(writer, clazz);
        }
        finally
        {
            Console.Write("Press any key to continue...");
            Console.ReadKey();
        }
    }

}

我可以想象XmlSerializer在公共属性上使用反射。

我一直在使用NetDataSerialiser类来序列化 我的域类。NetDataContractSerializer类。

域类在客户机和服务器之间共享。

当我创建一个具有数据类型-类型的属性时,我得到了相同的错误。在此,我得到了一个错误-有一个错误反射类型。我不断检查'InnerException'的每个异常从调试码头和得到特定的字段名(这是类型)在我的情况下。解决方法如下:

    [XmlIgnore]
    public Type Type { get; set; }