C# How to Serialize/Deserialize BitVector32
I have a class with a property of type BitVector32, when I Serialize it, I noticed the property was not getting serialized because the BitVector32 is not [Serializable].
After thinking about how can I serialize this property and looking into the implementation of BitVector32 it became clear that I need to approach this from a different angle.
BitVector32 class has a property called Data where the information is stored, this property is of type Int and Int is obviously [Serializable].
Here is my approach:
[Serializable] public class TreeItem { // Serializable requires an empty constructor public TreeItem() { } public int Id { get; set; } public int ObjectType { get; set; } [XmlIgnore] public BitVector32 Properties { get; set; } [XmlElement("Properties")] public Int32 Data { get { return Properties.Data; } set { Properties = new BitVector32(value); } } }
Here is how the serialized class looks like:
<TreeItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Id>1</Id>
<ObjectType>2</ObjectType>
<Properties>3</Properties>
</TreeItem>
Here is the test class:
using System.Collections.Specialized; using System.IO; using System.Linq; using ComplexSerialization.IO; using ComplexSerialization.Model; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Serialization.Tests { [TestClass] public class TreeItemTest { public TestContext TestContext { get; set; } private XmlSerializer<TreeItem> _subject; private string _filePath; [TestInitialize] public void TestInitialize() { _subject = new XmlSerializer<TreeItem>(); _filePath = Path.Combine(TestContext.TestDeploymentDir, "TreeItem.xml"); } [TestMethod] public void Serialize() { // Arrange var treeItem = new TreeItem { Id = 1, ObjectType = 2, Properties = new BitVector32(3) }; // Act _subject.Serialize(treeItem, _filePath); // Assert Assert.AreEqual(1, Directory.GetFiles(TestContext.TestDeploymentDir).ToList().Count(x=>x.Contains("TreeItem.xml"))); } } }
Comments
Post a Comment