问题
I have a business class which I need to serialize to xml. It has a BitArray property.
I have decorated it with [XmlAttribute]
but the serialization is failing with
To be XML serializable, types which inherit from ICollection must have an implementation of Add(System.Boolean) at all levels of their inheritance hierarchy. System.Collections.BitArray does not implement Add(System.Boolean).
I am not sure whether its possible to serialize to xml?
If not what would be an efficient means of serializing the BitArray
Thanks for looking
回答1:
You cannot directly serialize a BitArray to XML. The reason is that in order to de-serialize it you'd need an Add method which BitArray doesn't supply.
You can, however, copy it to an array that can be serialized:
BitArray ba = new BitArray(128);
int[] baBits = new int[4]; // 4 ints makes up 128 bits
ba.CopyTo(baBits, 0);
// Now serialize the array
Going the other way involves deserializing the array and calling the BitArray constructor:
int[] baBits; // This is deserialized somehow
BitArray ba = new BitArray(baBits);
If you do this, you'll want your BitArray size to be a multiple of the word size (i.e. if you use an array of int, then your BitArray size should be a multiple of 32).
回答2:
As something quick and dirty, how about create a property which has the [XmlAttribute], and it's getter return an array created from your BitArray by using the static BitArray.CopyTo method?
来源:https://stackoverflow.com/questions/2456713/can-i-serialize-a-bitarray-to-xml