Need to overwrite XMLWriter's method

风格不统一 提交于 2019-12-02 00:57:59

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.

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