Created
June 19, 2013 08:22
-
-
Save jwChung/5812597 to your computer and use it in GitHub Desktop.
SerializableMultidimensionalArray
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SerializableMultidimensionalArray : IXmlSerializable | |
{ | |
private readonly int[,] array = new int[3, 2]; | |
public int this[int i, int j] | |
{ | |
get | |
{ | |
return this.array[i, j]; | |
} | |
set | |
{ | |
this.array[i, j] = value; | |
} | |
} | |
public XmlSchema GetSchema() | |
{ | |
throw new NotSupportedException(); | |
} | |
public void ReadXml(XmlReader reader) | |
{ | |
if (reader.NodeType == XmlNodeType.Element && reader.Name == "SerializableMultidimensionalArray") | |
{ | |
reader.Read(); | |
while (reader.NodeType == XmlNodeType.Element && reader.Name == "ArrayElement") | |
{ | |
reader.ReadStartElement("ArrayElement"); | |
int i = reader.ReadElementContentAsInt(); | |
int j = reader.ReadElementContentAsInt(); | |
int value = reader.ReadElementContentAsInt(); | |
reader.ReadEndElement(); | |
this[i, j] = value; | |
} | |
} | |
} | |
public void WriteXml(XmlWriter writer) | |
{ | |
(from i in Enumerable.Range(0, this.array.GetLength(0)) | |
from j in Enumerable.Range(0, this.array.GetLength(1)) | |
select new | |
{ | |
I = i, | |
J = j, | |
Value = this[i, j] | |
}).ToList() | |
.ForEach(e => | |
{ | |
writer.WriteStartElement("ArrayElement"); | |
writer.WriteElementString("I", e.I.ToString()); | |
writer.WriteElementString("J", e.J.ToString()); | |
writer.WriteElementString("Value", e.Value.ToString()); | |
writer.WriteEndElement(); | |
}); | |
} | |
} | |
public class SerializableMultidimensionalArrayScenario | |
{ | |
[Fact] | |
public void Sut_ShouldBeSerializableAndDeserializable() | |
{ | |
// Arrange | |
var sut = new SerializableMultidimensionalArray(); | |
sut[1, 1] = 10; | |
var sb = new StringBuilder(); | |
var xmlSerializer = new XmlSerializer(typeof(SerializableMultidimensionalArray)); | |
// Act & Assert (Serializable) | |
xmlSerializer.Serialize(new StringWriter(sb), sut); | |
Assert.Contains("<Value>10</Value>", sb.ToString()); | |
// Act & Assert (Deserializable) | |
sut = (SerializableMultidimensionalArray)xmlSerializer.Deserialize(new StringReader(sb.ToString())); | |
Assert.Equal(10, sut[1, 1]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment