C#具有自定义类型的对象的序列化实践

时间:2012-05-22 09:24:44

标签: c# .net-3.5 binary-serialization

我创建了一些自定义类型,例如:

public class Temperature
{
    protected double _celcius;

    public Temperature(){}

    public Temperature(double celcius)
    {
        _celcius = celcius;
    }

    public double Celcius
    {
        //sets & returns temperature in Celcius
    }

    public double Fahrenheit
    {
        //sets & returns temperature in Fahrenheit
    }
}

Mass等类似的

我还有一个自定义对象,例如Planet,它使用这些自定义类型作为属性。

[Serializable]
public class Planet
{
    public int PositionFromSun;
    public Mass Mass;
    public Temperature Temperature;
}

考虑到PlanetMass将来可能略有变化(例如将Temperature添加到Kelvin,在这种情况下序列化Temperature的最佳做法是什么? })?我应该MassTemperature继承自IQuantity之类的自定义界面。

2 个答案:

答案 0 :(得分:1)

请参阅@Adriano的comment。这就是我需要的。

  

是的,您可以根据需要添加任意数量的公共属性。为了进行比较,请在此处查看此帖子:What are the differences between the XmlSerializer and BinaryFormatter

答案 1 :(得分:0)

二进制序列化对于添加和删除类型的属性非常挑剔。如果您使用版本容错的序列化程序(例如基于xml的序列化程序),您将能够在类的版本之间可靠地序列化/反序列化。

您可能需要考虑使用protobuf.Net进行序列化 - 它已经成熟,非常快速且版本容忍。