Need to overwrite XMLWriter's method

2019-02-25 23:45发布

I need to overwrite the XMLWriter's method "WriteElementString" to not write the element if the value is empty, the code bellow didn't work, tried override and new keywords but it still goes to the framework method.

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

The answer was close but correct solution is:

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);
        }
    }
}

1条回答
我命由我不由天
2楼-- · 2019-02-26 00:36

You need to create an object that decorates XmlWriter to achieve what you are trying to do. More on the Decorator Pattern

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 implemented using Decorator Pattern
    // i.e.
    public override void Close()
    {
        this.writer.Close();
    }
    ...
}

using (var writer = XmlWriter.Create(XMLBuilder, XMLSettings))
using (var myWriter = new MyXmlWriter (writer))
{
    // use myWriter in here to construct XML
}

What you are trying to do, is to override a method using an extension method which is not what they are intended to do. See the Binding Extension Methods at Compile Time section on the Extension Methods MSDN Page The compiler will always resolve WriteElementString to the instance implemented by XmlWriter. You would need to manually call your extension method XmlWriterExtensions.WriteElementString(writer, localName, value); in order for your code to execute as you have it.

查看更多
登录 后发表回答