序列化已排序的集合成员
本文关键字:集合 成员 排序 序列化 | 更新日期: 2023-09-27 18:16:04
我有一个从排序集派生的类,它有一些成员:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Application.Model
{
[Serializable]
public class Trajectory : SortedSet<PolarPosition>
{
public delegate void DataChangedEventHandler();
public event DataChangedEventHandler DataChanged = delegate { };
public Trajectory()
: base(new PolarPositionComparer())
{
this.Name = "new one";
}
public Trajectory(IComparer<PolarPosition> comparer)
: base(comparer)
{
this.Name = "new compared one";
}
public Trajectory(IEnumerable<PolarPosition> listOfPoints)
: base(listOfPoints, new PolarPositionComparer())
{
this.Name = "new listed one";
}
public Trajectory(SerializationInfo info, StreamingContext context)
: base(info, context)
{ }
public string Name { get; set; }
public CoordinateSystemEnum UsedCoordinateSystem { get; set; }
public new bool Add(PolarPosition point)
{
DataChanged();
return base.Add(point);
}
}
}
与此enum:
[Serializable]
public enum CoordinateSystemEnum
{
Polar,
Cartesian
}
this比较器:
[Serializable]
public class PolarPositionComparer : IComparer<PolarPosition>
{
...
}
和this PolarPosition:
[Serializable]
public class PolarPosition
{
public double Radius { get; set; }
public double Phi { get; set; }
}
我想保存序列化和反序列化它。我使用了这个线程的答案:用内存流序列化/反序列化,代码片段看起来像:
var trajectory1 = new Trajectory {
new PolarPosition(10, 2),
new PolarPosition(11, 2),
new PolarPosition(12, 2)
};
trajectory1.Name = "does ont matter";
trajectory1.UsedCoordinateSystem = CoordinateSystemEnum.Cartesian;
var memoryStreamOfTrajectory1 = SerializeToStream(trajectory1);
var deserializedTrajectory1 = DeserializeFromStream(memoryStreamOfTrajectory1);}
现在我的问题是,deserializedTrajectory1.Name
总是null
, deserializedTrajectory1.UsedCoordinateSystem
总是Polar
。
我做错了什么?
SortedSet<T>
类实现ISerializable
。根据自定义序列化文档:
当你从一个实现了isserializable的类派生一个新类时,派生类必须实现构造函数[接受SerializationInfo和StreamingContext参数]以及GetObjectData方法(如果它有需要序列化的变量)。
因此,要序列化/反序列化Name
和UsedCoordinateSystem
属性,需要添加以下逻辑:
[Serializable]
public class Trajectory : SortedSet<PolarPosition>
{
protected override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("Name", this.Name);
info.AddValue("UsedCoordinateSystem", (int)this.UsedCoordinateSystem);
}
public Trajectory(SerializationInfo info, StreamingContext context)
: base(info, context)
{
this.Name = info.GetString("Name");
this.UsedCoordinateSystem = (CoordinateSystemEnum)info.GetInt32("UsedCoordinateSystem");
}
}