包装类的序列化与嵌套类的字典?

时间:2013-12-22 18:03:35

标签: c# serialization dictionary deserialization

我有两个需要序列化为文件的类。这是基本的Item类。

[Serializable()]
public class Item:ISerializable,...
{
    ......
    private string _itemName;

    [NonSerialized]
    private Inventory _myInventory;

    private double _weight;
    ....

    event PropertyChangingEventHandler propertyChanging;
    event PropertyChangingEventHandler INotifyPropertyChanging.PropertyChanging
    {
        add { propertyChanging += value;}
        remove { propertyChanging -= value; }
    }

    public string Name {get;set;....}
    public double Weight {get;set;...}
    ....

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("Name", _itemName);
        info.AddValue("Weight", _weight);

        Type t = this.GetType();
        info.AddValue("TypeObj", t);
    }

    internal Item(SerializationInfo info, StreamingContext context) 
    {
        _itemName = info.GetString("Name");
        _weight = info.GetDouble("Weight");
    }

这是库存类:

   [Serializable()]
   public class Inventory:......
   {
       private int _numOfProduct = 0;
       private int _numOfItems = 0;

       private Dictionary<string, Item> _inventoryDictionary = new Dictionary<string, Item>();
       .....

       public IEnumerable<Item> GetSortedProductsByName()
       {
        return _inventoryDictionary.OrderBy(key => key.Key).Select(key => key.Value).ToList();
       }

       .....
   }

当我使用以下函数测试二进制序列化到文件时

   //serialize 
   ....
   fs = File.OpenWrite(FileName);  //FileName = "C:/temp/foo.bin"
   b.Serialize(fs, products); 
   fs.Close(); 

   ....
   //deserialize 
   Inventory products = new Inventory();
   BinaryFormatter b = new BinaryFormatter();
   fs = File.OpenRead(FileName);
   products = (Inventory)b.Deserialize(fs);
   ...

当我测试序列化时,似乎以下代码无法按预期工作:       ....       foreach(products中的var item.GetSortedProductsByName())                             {                                 Console.WriteLine(item.Name);                             }       ....

我通过这些行进行了调试,发现该项始终为null,尽管product不为null。

有什么想法吗?

如果有人知道某个地方我可以找到类似我的方案的示例实现,请告诉我。

0 个答案:

没有答案