开发者

Serializing a BigInteger

开发者 https://www.devze.com 2023-03-21 13:03 出处:网络
Is there any method of serializing a BigInteger to and from an XML file? Below is a short snippet that demonstrates how I\'m currently serializing classes:

Is there any method of serializing a BigInteger to and from an XML file?

Below is a short snippet that demonstrates how I'm currently serializing classes:

static public void Serialize开发者_开发技巧ToXML( Report report )
{
    XmlSerializer serializer = new XmlSerializer( typeof( Report ) );
    using ( TextWriter textWriter = new StreamWriter( Path.Combine( report.Path, report.Filename ) ) )
    {
        serializer.Serialize( textWriter, report );
    }
}

[Serializable]
public class Report
{
    public BigInteger CurrentMaximum { get; set; }
}

All other properties within the Report class get serialized correctly, however, the BigInteger properties do not. Is there a way to serialize this property?


Unfortunately XmlSerializer is designed to create XML describeable using a standard XML Schema; that were in the framework during the .Net 1.0 phase (which means xs:integer isn't supported).

IXmlSerializable

You will need to modify the BigInteger class and add the IXmlSerializable interface to it. If you need to use XSD round-tripping (e.g. WebService references) this might cause problems.

public class BigInteger : IXmlSerializable
{
    public int Value;

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        // You should really a create schema for this.
        // Hardcoded is fine.
        return null;
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        Value = int.Parse(reader.ReadString());
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        writer.WriteValue(Value.ToString());
    }
}

Proxy Property (Although this looks like it has code-smell it is way more portable)

Create a new property with a supported schema type (most probably xs:string) and hide it from intellisense.

[XmlRoot("foo")]
public class SerializePlease
{
    [XmlIgnore]
    public BigInteger BigIntValue;

    [XmlElement("BigIntValue")]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public string BigIntValueProxy
    {
        get
        {
            return BigIntValue.ToString();
        }
        set
        {
            BigIntValue = BigInteger.Parse(value);
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号