C# 使用嵌套类的字典对包装类进行序列化?

C# 使用嵌套类的字典对包装类进行序列化?,c#,serialization,dictionary,deserialization,C#,Serialization,Dictionary,Deserialization,我有两个类需要序列化为一个文件。下面是基本的Item类 [Serializable()] public class Item:ISerializable,... { ...... private string _itemName; [NonSerialized] private Inventory _myInventory; private double _weight; .... event PropertyChangingEven

我有两个类需要序列化为一个文件。下面是基本的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();
       }

       .....
   }
当我测试序列化时,以下代码似乎无法按预期工作: .... 用于products.GetSortedProductsByName中的每个var项 { Console.WriteLineitem.Name; }

我对这些行进行了调试,发现尽管product不为null,但item始终为null

有什么想法吗


如果有人知道我可以在哪里找到类似的场景示例,请告诉我。

与论坛网站不同,我们不使用感谢、感谢的帮助或签名。看,你必须包含再现问题的完整代码。我看不出该代码有任何问题,您在这里展示的内容不会产生您在运行时描述的问题。
   //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);
   ...