我正在为一个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
?