本文介绍了C#XML的采用序列化的IXmlSerializable派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类,它是XML序列化和实现IXmlSerializable的派生类兼容

I've got a base class which is compatible with XML serialization and a derived class which implements IXmlSerializable.

在这个例子中,基类实现IXmlSerializable的:使用System.Diagnostics程序

In this example, the base class does implement IXmlSerializable:


using System.Diagnostics;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace XmlSerializationDerived
{
    public class Foo
    {
    	public int fooProp;

    	public XmlSchema GetSchema()
    	{
    		return null;
    	}

    	public void ReadXml(XmlReader reader)
    	{
    		fooProp = int.Parse (reader.ReadElementString ("fooProp"));
    	}

    	public void WriteXml(XmlWriter writer)
    	{
    		writer.WriteElementString ("fooProp", fooProp.ToString ());
    	}
    }

    public class Bar : Foo, IXmlSerializable
    {
    	public new void ReadXml(XmlReader reader)
    	{
    		base.ReadXml (reader);
    	}

    	public new void WriteXml(XmlWriter writer)
    	{
    		base.WriteXml (writer);
    	}

    	static void Main(string[] args)
    	{
    		StringBuilder sb = new StringBuilder ();
    		XmlWriter writer = XmlWriter.Create (sb);

    		Bar bar = new Bar ();
    		bar.fooProp = 42;

    		XmlSerializer serializer = new XmlSerializer (typeof (Bar));
    		serializer.Serialize (writer, bar);

    		Debug.WriteLine (sb.ToString ());
    	}
    }
}

这会产生这样的输出:

<?xml version="1.0" encoding="utf-16"?><Bar><fooProp>42</fooProp></Bar>



不过,我想用一个基类,它做的不是实现IXmlSerializable的。这样可以防止使用 base.Read/WriteXml 。其结果将是:

However, i'd like to use a base class which does not implement IXmlSerializable. This prevents using base.Read/WriteXml. The result will be:

<?xml version="1.0" encoding="utf-16"?><Bar />

有什么办法仍然得到期望的结果?

Is there any way to still get the desired result?

推荐答案

这样可以防止使用base.Read/WriteXml。

" This prevents using base.Read/WriteXml."

通常,如果基类实现的IXmlSerializable ,你可能会因此所使用的具体版本,使其成为虚拟方法。通常情况下,你也最好使用显式实现(而非公共属性) - 也许与实施细则的一些受保护的虚拟方法(虽然跟踪在那里读/写器是在不同的类别将是一场噩梦)。

Typically, if the base-class implemented IXmlSerializable, you might make it a virtual method so that the concrete version is used. Typically, you'd also use explicit implementation (rather than public properties) - perhaps with some protected virtual methods for the implementation details (although keeping track of where the reader/writer is across different classes would be a nightmare).

据我所知,是没有办法再使用的XmlSerializer 写在的位,当你添加的导出的位。 的IXmlSerializable 是全有或全无。

AFAIK, there is no way to re-use XmlSerializer to write the base bits, while you add the derived bits. IXmlSerializable is all-or-nothing.

这篇关于C#XML的采用序列化的IXmlSerializable派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 15:09