【问题标题】:Binary serialization of whole class automatically整个类的二进制序列化自动
【发布时间】:2014-12-10 02:43:53
【问题描述】:

有没有一种方法可以序列化/反序列化整个类而无需指定每个对象。

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

例如:

[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);
        }
    }

【问题讨论】:

标签: c# winforms serialization binary-serialization


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多