-1

我正在为一个Collection<T>类编写序列化代码,并且想知道如何设置和获取集合中的项目。我正在使用二进制序列化。

我在以下代码中进行了尝试,但不确定正确的方法。

这是我的代码:

[Serializable]
public class EmployeeCollection<Employee> : Collection<Employee>, ISerializable
{
    public int EmpId;
    public string EmpName;
    public EmployeeCollection()
    {
        EmpId = 1;
        EmpName = "EmployeeCollection1";
    }
    public EmployeeCollection(SerializationInfo info, StreamingContext ctxt)
    {
        EmpId = (int)info.GetValue("EmployeeId", typeof(int));
        EmpName = (String)info.GetValue("EmployeeName", typeof(string));
        //Not sure on the correct code for the following lines
        var EmployeeCollection = (List<Employee>)info.GetValue("EmployeeCollection", typeof(List<Employee>));
        for (int i = 0; i < EmployeeCollection.Count; i++)
        {
            this.Add(EmployeeCollection[i]);
        }
    }

    public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
    {
        info.AddValue("EmployeeId", EmpId);
        info.AddValue("EmployeeName", EmpName);
        //Not sure on the correct code for the following lines
        var EmployeeCollection = new List<Employee>();
        for (int i = 0; i < this.Count; i++)
        {
            EmployeeCollection.Add(this[i]);
        }
        info.AddValue("EmployeeCollection", EmployeeCollection);
    }

在该GetObjectData方法中,List<Employee>添加SerializationInfo成功。但是,在该EmployeeCollection方法中,每个添加的项目List<Employee>都有一个null条目。

Collection<T>实现接口时如何正确序列化和反序列化类中的项目ISerializable

4

1 回答 1

0

与其花时间编写 BinaryFormatter 所需的自定义序列化,不如试试AnySerializer。您不需要编写任何序列化代码,并且内置了对泛型集合的支持。您可以省略该[Serializable]属性,并摆脱 ISerializable 接口。如果它适合你,请告诉我,因为我是作者。

一个工作示例:

public class EmployeeCollection<Employee> : Collection<Employee>
{
    public int EmpId;
    public string EmpName;
    public EmployeeCollection()
    {
        EmpId = 1;
        EmpName = "EmployeeCollection1";
    }
}

// serialize/deserialize
using AnySerializer;

var collection = new EmployeeCollection();
var bytes = Serializer.Serialize(collection);
var restoredCollection = Serializer.Deserialize<EmployeeCollection<Employee>>(bytes);
于 2018-11-29T07:42:52.243 回答