gpt4 book ai didi

c# - 为版本控制实现 ISerializable

转载 作者:行者123 更新时间:2023-11-30 16:09:54 24 4
gpt4 key购买 nike

考虑以下类的 POD 类型:

public class Price { public decimal OfferPrice { get; set; } }

此类的对象是从服务器检索的,所以让我们用可序列化来装饰它

[Serializable]
public class Price { public decimal OfferPrice { get; set; } }

现在有两个客户端在不同的机器上检索这些对象。他们不会发送价格。他们都得到了普赖斯集会的副本。

现在类扩展了 BonusPrice。

[Serializable]
public class Price {
public decimal OfferPrice { get; set; }
public decimal BonusPrice { get; set; }
}

新程序集被部署到服务器,部署到其中一个客户端而不是另一个。因此,旧版本的客户端在(反)序列化 Price 对象时会崩溃。

具有旧版本的客户端不需要 BonusPrice 字段,因此当存在版本差异时它继续工作会很好。因此,我正在考虑从一开始就实现 ISerializable,因此第一个和第二个版本看起来像:

// version 1.0
[Serializable]
public class Price : ISerializable {
protected Price(SerializationInfo info, StreamingContext context) {
OfferPrice = info.GetDecimal("op");
}

[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context) {
info.AddValue("op", OfferPrice);
}
}

// version 2.0
[Serializable]
public class Price : ISerializable {
protected Price(SerializationInfo info, StreamingContext context) {
OfferPrice = info.GetDecimal("op");
BonusPrice = info.GetDecimal("bp");
}

[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context) {
info.AddValue("op", OfferPrice);
info.AddValue("bp", BonusPrice);
}
}

所以现在当一个客户端没有更新到版本 2 时,它仍然会继续反序列化 OfferPrice 而不会崩溃。当它在某个时候更新时,它会自动使用 BonusPrice。

我的问题:在仅读取对象时,实现 ISerializable 是否是进行版本控制的好方法?这些问题通常是如何解决的?

最佳答案

您可以使用 OptionalFieldAttribute控制 BinaryFormatterSoapFormatter 的版本控制。

The OptionalFieldAttribute has the VersionAdded property. In version 2.0 of the .NET Framework, this is not used. However, it is important to set this property correctly to ensure that the type will be compatible with future serialization engines.

The property indicates which version of a type a given field has been added. It should be incremented by exactly one (starting at 2) every time the type is modified

还有其他方法,如序列化回调、SerializationBinder、ISerializable 等。

引用Version Tolerant Serialization了解更多信息。

关于c# - 为版本控制实现 ISerializable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26860297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com