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

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

我得到一个异常说:

有错误反射类型。

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


当前回答

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

Or

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

其他回答

我认为最常见的原因是:

 - the object being serialized has no parameterless constructor
 - the object contains Dictionary
 - the object has some public Interface members

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

到目前为止,我有一个稍微不同的解决方案,所以对于任何未来的文明,这里是我的!

我已经声明了一个“时间”的数据类型,因为原始类型是TimeSpan,随后更改为字符串:

[System.Xml.Serialization.XmlElementAttribute(DataType="time", Order=3)]

然而,实际的类型是字符串

public string TimeProperty {
    get {
        return this.timePropertyField;
    }
    set {
        this.timePropertyField = value;
        this.RaisePropertyChanged("TimeProperty");
    }
}

通过删除DateType属性,Xml可以被序列化

[System.Xml.Serialization.XmlElementAttribute(Order=3)]
public string TimeProperty {
    get {
        return this.timePropertyField;
    }
    set {
        this.timePropertyField = value;
        this.RaisePropertyChanged("TimeProperty");
    }
}
[System.Xml.Serialization.XmlElementAttribute("strFieldName", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]

Or

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

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

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