我可以将 BitArray 序列化为 XML 吗? [英] Can I serialize a BitArray to XML?

查看:29
本文介绍了我可以将 BitArray 序列化为 XML 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个业务类,我需要将其序列化为 xml.它有一个 BitArray 属性.

I have a business class which I need to serialize to xml. It has a BitArray property.

我已经用 [XmlAttribute] 修饰了它,但是序列化失败了

I have decorated it with [XmlAttribute] but the serialization is failing with

要进行 XML 序列化,从 ICollection 继承的类型必须在其继承层次结构的所有级别都实现 Add(System.Boolean).System.Collections.BitArray 没有实现 Add(System.Boolean).

我不确定是否可以序列化为 xml?

I am not sure whether its possible to serialize to xml?

如果不是,序列化 BitArray 的有效方法是什么

If not what would be an efficient means of serializing the BitArray

感谢关注

推荐答案

您不能直接将 BitArray 序列化为 XML.原因是为了反序列化它,您需要一个 BitArray 不提供的 Add 方法.

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

另一种方式涉及反序列化数组并调用 BitArray 构造函数:

Going the other way involves deserializing the array and calling the BitArray constructor:

int[] baBits;  // This is deserialized somehow
BitArray ba = new BitArray(baBits);

如果你这样做,你会希望你的 BitArray 大小是字大小的倍数(即如果你使用一个 int 数组,那么你的 BitArray 大小应该是 32 的倍数).

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).

这篇关于我可以将 BitArray 序列化为 XML 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆