需要覆盖XMLWriter's方法

本文关键字:方法 覆盖 XMLWriter | 更新日期: 2023-09-27 17:49:59

我需要覆盖XMLWriter的方法"WriteElementString"不写元素,如果值是空的,下面的代码不起作用,尝试覆盖新的关键字,但它仍然去框架方法。

public static void WriteElementString(this XmlWriter writer,
                                      string localName,
                                      string value)
{
    if (!string.IsNullOrWhiteSpace(value))
    {
        writer.WriteStartElement(localName);
        writer.WriteString(value);
        writer.WriteEndElement();
    }
}

答案很接近,但正确的答案是:

public abstract class MyWriter : XmlWriter
{
    private readonly XmlWriter writer;
    public Boolean skipEmptyValues;
    public MyWriter(XmlWriter writer)
    {
        if (writer == null) throw new ArgumentNullException("Writer");
        this.writer = writer;
    }
    public new void WriteElementString(string localName, string value)
    {
        if (string.IsNullOrWhiteSpace(value) && skipEmptyValues)
        {
            return;
        }
        else
        {
            writer.WriteElementString(localName, value);
        }
    }
}

需要覆盖XMLWriter's方法

您需要创建一个对象来装饰XmlWriter以实现您想要做的事情。关于Decorator模式的更多信息

public class MyXmlWriter : XmlWriter
{
    private readonly XmlWriter writer;
    public MyXmlWriter(XmlWriter writer)
    {
        if (writer == null) throw new ArgumentNullException("writer");
        this.writer = writer;
    }
    // This will not be a polymorphic call
    public new void WriteElementString(string localName, string value)
    {
        if (string.IsNullOrWhiteSpace(value)) return;
        this.writer.WriteElementString(localName, value);
    }
    // the rest of the XmlWriter methods will need to be implemented using Decorator Pattern
    // i.e.
    public override void Close()
    {
        this.writer.Close();
    }
    ...
}

在LinqPad中使用上述对象

var xmlBuilder = new StringBuilder();
var xmlSettings = new XmlWriterSettings
{
    Indent = true
};
using (var writer = XmlWriter.Create(xmlBuilder, xmlSettings))
using (var myWriter = new MyXmlWriter(writer))
{
    // must use myWriter here in order for the desired implementation to be called
    // if you pass myWriter to another method must pass it as MyXmlWriter
    //    in order for the desired implementation to be called
    myWriter.WriteStartElement("Root"); 
    myWriter.WriteElementString("Included", "Hey I made it");
    myWriter.WriteElementString("NotIncluded", "");
}
xmlBuilder.ToString().Dump();
输出:

<?xml version="1.0" encoding="utf-16"?>
<Root>
  <Included>Hey I made it</Included>
</Root>

你要做的,是用一个扩展方法重写一个方法,这不是他们想要做的。请参阅扩展方法MSDN页面上的"编译时绑定扩展方法"一节。编译器总是将WriteElementString解析为XmlWriter实现的实例。您需要手动调用您的扩展方法XmlWriterExtensions.WriteElementString(writer, localName, value);,以便您的代码按照您所拥有的方式执行。