我正在重构我的 XML 序列化,并想尝试一下 DataContractSerializer。

using System;
using System.Runtime.Serialization;

namespace VDB_Sync.Model
{
[DataContract(Name="Konstant")]
public class Konstant : DataFelt
{
    [DataMember]
    private MySqlDbType mydataType;
    [DataMember]
    private object value;

    public Konstant(string navn, MySqlDbType dataType, object value)
        : base(navn, dataType, "*Konstant", false, false)
    {
        //this.navn = navn;
        this.mydataType = dataType;
        this.value = value;

        if (navn.Contains("*Løbenummer"))
        {
            navn = "*Konstant: " + Convert.ToString(value);
        }
    }

    public object Value
    {
        get
        {
            return value;
        }
    }

}
}

它给了我这个:

Type ‘VDB_Sync.Model.Konstant’ with data contract name ‘Konstant:http://schemas.datacontract.org/2004/07/VDB_Sync.Model’ is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.

*到目前为止我找到的帮助指向集合和类型。

作为参考,这就是我序列化它的方式,VDB_SessionController 是根:*

    public void GemKonfig(VDB_SessionController session)
    {
        var settings = new XmlWriterSettings()
        {
            Indent = true,
            IndentChars = "\t"
        };

        var writer = XmlWriter.Create(defaultFile, settings);
        DataContractSerializer ser =
            new DataContractSerializer(typeof(VDB_SessionController));

        ser.WriteObject(writer, session);
        writer.Close();
    }

答案

报告的异常是针对 VDB_Sync.Model.Konstant 的。

问题是,根据 Konstant 在此类中的嵌入方式(例如,如果它位于集合或通用列表中),DataContractSerializer 可能无法在反序列化期间准备好其出现。

要解决此问题,您需要将known-type 属性应用于包含 Konstant 的类。VDB_SessionController

因此,尝试使用 KnownType 属性来修饰此类:

[KnownType(typeof(VDB_Sync.Model.Konstant)]
public class VDB_SessionController

来自: stackoverflow.com