据作者说用.NET框架自带的序列化和反序列化方法效率不高,而Berkeley DB for .NET里带有自己的序列化反序列化办法。
首先假设我们有如下的类的实例要序列化后存入DB,和从DB反序列化出来:
(三个类Vendor 、SalesRep、StockItems,下面只举StockItems的例子)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
StockItem
public class StockItem
{
internal string name;
internal string sku;
internal float? price;
internal int? quantity;
public string Name {
get { return name; }
set { name = value; }
}
public string Sku {
get { return sku; }
set { sku = value; }
}
public float? Price {
get { return price; }
set { price = value; }
}
public int? Quantity {
get { return quantity; }
set { quantity = value; }
}
}
然后我们定义一个继承ReferenceField<T>的类:
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
public class StockItemField: ReferenceField<StockItem>
{
public StockItemField(Formatter fmt, bool isDefault): base(fmt, isDefault) { }
protected override void SerializeValue(StockItem value) {
Fmt.Serialize<string>(value.name);
Fmt.Serialize<string>(value.sku);
Fmt.Serialize<float>(value.price);
Fmt.Serialize<int>(value.quantity);
}
protected override void DeserializeInstance(ref StockItem instance) {
if (instance == null)
instance = new StockItem();
}
protected override void DeserializeMembers(StockItem instance) {
Fmt.Deserialize<string>(ref instance.name);//引用类型这样反序列化
Fmt.Deserialize<string>(ref instance.sku);
instance.price = Fmt.Deserialize<float>();//值类型这样反序列化
instance.quantity = Fmt.Deserialize<int>();
}
protected override void SkipValue() {
if (Fmt.Skip<string>())
if (Fmt.Skip<string>())
if (Fmt.Skip<float>())
Fmt.Skip<int>();
}
}
准备工作做好了,以下是正式干活:
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
// 初始化(分了3个,那是因为用到3个ReferenceField<T>的子类。
BdbFormatter formatter = new BdbFormatter(3, 2048);
// 注册
//VendorField/SalesRepField这些就不赘述了
new VendorField(formatter, true);
new SalesRepField(formatter, true);
new StockItemField(formatter, true);
// 创建Vendor, SalesRep, StockItem的实例
Vendor vendor = new Vendor();
![](https://www.cnblogs.com/Images/dot.gif)
// 序列化 Vendor (以及SalesRep 、StockItems)
DbEntry vendorEntry = formatter.ToDbEntry<Vendor>(vendor);
// 反序列化Vendor对象
vendor = null;
formatter.FromDbEntry<Vendor>(ref vendor);