可为Collection <t>

时间:2018-11-26 23:12:05

标签: c# collections binary-serialization iserializable

我正在为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类中的项目?

1 个答案:

答案 0 :(得分:0)

请尝试AnySerializer,而不是花时间编写BinaryFormatter所需的自定义序列化。您无需编写任何序列化代码,并且内置了对通用集合的支持。您可以省略[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);