我需要覆盖XMLWriter的方法&#34; WriteElementString&#34;如果值为空,则不写元素,下面的代码不起作用,尝试覆盖和新关键字,但它仍然转到框架方法。< / p>
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);
}
}
}
答案 0 :(得分:4)
您需要创建一个装饰XmlWriter
的对象,以实现您的目标。 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
}
您要做的是使用扩展方法覆盖方法,这不是他们想要做的。请参阅扩展方法MSDN页面上的Binding Extension Methods at Compile Time部分编译器将始终将WriteElementString
解析为XmlWriter
实现的实例。您需要手动调用扩展方法XmlWriterExtensions.WriteElementString(writer, localName, value);
,以便您的代码可以执行。