Need to overwrite XMLWriter's method

前端 未结 1 1224
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-19 06:54

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

1条回答
  •  悲哀的现实
    2021-01-19 07:05

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

    Using the above object in 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();
    

    Output:

    
    
      Hey I made it
    
    

    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.

    0 讨论(0)
提交回复
热议问题