序列化异常:不期望数据合同

时间:2013-02-17 13:05:27

标签: c# serialization

在将对象序列化为XML时,我收到以下异常消息:

{"Type 'Alerter.EmailSender' with data contract name  'EmailSender:http://schemas.datacontract.org/2004/07/Alerter' 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."}

这是我尝试将其对象序列化为XML文件的类:

namespace Alerter
{
  [DataContract]
  public class EmailSender : IAction
  {
    private EmailSetting _emailSetting;
    private SmtpClient _smtpClient;
    [DataMember]
    public bool IncludeFullDetails
    {
        get;
        set;
    }
    [DataMember]
    public string[] Receivers
    {
        get;
        set;
    }

    public EmailSender()
    {
        _emailSetting = new EmailSetting();
        SetupClient();
    }

    private void SetupClient()
    {
        // Some Logic
    }


    public void Report(LogDictionary logDictionary)
    {
       // Some Logic
    }
   }
 }

这是我用于序列化的代码:

 using (FileStream writer = new FileStream(fileName, FileMode.Create))
        {
            DataContractSerializer ser =
                new DataContractSerializer(typeof(List<Rule>));
            ser.WriteObject(writer, list);
        }

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

确保使用proper constructor将此EmailSender类指定为序列化程序的已知类型:

DataContractSerializer ser = new DataContractSerializer(
    typeof(List<Rule>), 
    new[] { typeof(EmailSender) }
);
ser.WriteObject(writer, list);

你需要这个的原因是因为可能在Rule类的对象图中你只为所有成员使用了IAction接口而且序列化器甚至都不知道是否存在EmailSender实施。

对于Rule对象图中未静态知道的所有其他类型,您应该这样做。