无法创建抽象类或接口的实例' system.xml.XmlWriter'

时间:2014-09-02 09:45:20

标签: c#

我在Xml序列化中也遇到了高级OOP和设计模式的问题 这将是我的代码:

    public void Send(Message message, string recipient)
    {
        XmlSerializer ser = new XmlSerializer(typeof(XmlNode));
        XmlWriter writer = new XmlWriter(Messenger.outbox + message.Recipient);
        ser.Serialize(writer, message);
        writer.Close();
    }

2 个答案:

答案 0 :(得分:0)

您无法实例化抽象类,而是在寻找XmlWriter.Create方法。

  

使用指定的文件名创建新的XmlWriter实例。

答案 1 :(得分:0)

您不能直接创建new XmlWriter,而是使用XmlWriter静态类来创建编写器实例。

鉴于课程Message

public class Message
{
    public string Outbox { get; set; }
    public string Recipient { get; set; }
}

您可以像这样序列化它:

XmlSerializer ser = new XmlSerializer(typeof(Message));
using (StringWriter sww = new StringWriter())
{
    using (XmlWriter writer = XmlWriter.Create(sww))
    {
        ser.Serialize(writer, new Message() { Outbox = "onething", Recipient = "another thing" });
        var xml = sww.ToString();
    }
}