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

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

我得到一个异常说:

有错误反射类型。

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


当前回答

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

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

其他回答

看看你得到的内部异常。它将告诉您序列化哪个字段/属性有问题。

您可以通过使用[XmlIgnore]属性来装饰xml序列化中的字段/属性来排除它们。

XmlSerializer没有使用[Serializable]属性,所以我怀疑这是问题所在。

[System.Xml.Serialization.XmlElementAttribute("strFieldName", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]

Or

[XmlIgnore]
string [] strFielsName {get;set;}

我刚刚得到了同样的错误,并发现类型IEnumerable<SomeClass>的属性是问题所在。IEnumerable似乎不能直接序列化。

相反,可以使用List<SomeClass>。

我也认为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在公共属性上使用反射。

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

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

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