Binary serialization of whole class automatically

88 Views Asked by At

Is there a way to serialize/deserialize a whole class without having to specify each object.

If I plan to add many more items, this will become tedious.

For example:

[Serializable()]
    public class Items : ISerializable
    {
        public List<Product> ProdList;
        public List<Employee> EmpList;
        public List<ListProduct> BuyList;
        public List<ListProduct> SellList;
        public List<ListEmployee> EmpHours;

        public Items()
        {
            ProdList = new List<Product>();
            EmpList = new List<Employee>();
            BuyList = new List<ListProduct>();
            SellList = new List<ListProduct>();
            EmpHours = new List<ListEmployee>();
        }

        public Items(SerializationInfo info, StreamingContext ctxt)
        {
            ProdList = (List<Product>)info.GetValue("ProdList", typeof(List<Product>));
            BuyList = (List<ListProduct>)info.GetValue("BuyList", typeof(List<ListProduct>));
            SellList = (List<ListProduct>)info.GetValue("SellList", typeof(List<ListProduct>));
            EmpList = (List<Employee>)info.GetValue("EmpList", typeof(List<Employee>));
            EmpHours = (List<ListEmployee>)info.GetValue("EmpHours", typeof(List<ListEmployee>));
        }

        public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
        {
            info.AddValue("ProdList", ProdList);
            info.AddValue("BuyList", BuyList);
            info.AddValue("SellList", SellList);
            info.AddValue("EmpList", EmpList);
            info.AddValue("EmpHours", EmpHours);
        }
    }
1

There are 1 best solutions below

0
On

If you don't want to use helper classes like DataContractSerializer and insist on implementing the ISerializable interface you can use reflection to iterate all item properties in this class and set their corresponding values.