Need to overwrite XMLWriter's method

不问归期 提交于 2019-12-02 05:42:15

问题


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:


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.



来源:https://stackoverflow.com/questions/22364889/need-to-overwrite-xmlwriters-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!