全自动二进制序列化

时间:2014-12-10 02:43:53

标签: c# winforms serialization binary-serialization

是否可以在不必指定每个对象的情况下序列化/反序列化整个类。

如果我计划添加更多项目,这将变得乏味。

例如:

[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 个答案:

答案 0 :(得分:0)

如果您不想使用DataContractSerializer之类的辅助类并坚持实现ISerializable接口,您可以使用反射来迭代此类中的所有项属性并设置其相应的值。