2015-12-28 46 views
0

我想保存和加載在c#序列化。但是,我在加載時遇到問題,我不確定我是否明白問題所在。下面是代碼:反序列化BinaryFormatter的c#

[Serializable] 
public class Network : ISerializable 
{ 
    private static readonly string _FILE_PATH = "Network.DAT"; 

    //properties 
    public List<Component> MyComponents { get; private set; } 
    public List<Pipeline> Pipelines { get; private set; } 

    public Network() 
    { 
     this.MyComponents = new List<Component>(); 
     this.Pipelines = new List<Pipeline>(); 
    } 
    public Network(SerializationInfo info, StreamingContext context) 
    { 
     this.MyComponents = (List<Component>)info.GetValue("MyComponents", MyComponents.GetType()); 
     this.Pipelines = (List<Pipeline>)info.GetValue("Pipelines", Pipelines.GetType()); 
    } 
    **//Methods** 
    public static void SaveToFile(Network net) 
    { 
     using (FileStream fl = new FileStream(_FILE_PATH, FileMode.OpenOrCreate)) 
     { 
      BinaryFormatter binFormatter = new BinaryFormatter(); 
      binFormatter.Serialize(fl,net); 
     } 
    } 
    public static Network LoadFromFile() 
    { 
     FileStream fl = null; 
     try 
     { 
      fl = new FileStream(_FILE_PATH, FileMode.Open); 
      BinaryFormatter binF = new BinaryFormatter(); 
      return (Network)binF.Deserialize(fl); 

     } 
     catch 
     { 
      return new Network(); 
     } 
     finally 
     { 
      if (fl != null) 
      { 
       fl.Close(); 
      } 
     } 
    } 

    public void GetObjectData(SerializationInfo info, StreamingContext context) 
    { 
     info.AddValue("MyComponents", MyComponents); 

     info.AddValue("Pipelines", Pipelines); 

    } 

,我得到的錯誤是:

An exception of type 'System.NullReferenceException' occurred in ClassDiagram-Final.exe but was not handled in user code 

Additional information: Object reference not set to an instance of an object. 

謝謝!

回答

0

問題是這裏

public Network(SerializationInfo info, StreamingContext context) 
{ 
    this.MyComponents = (List<Component>)info.GetValue("MyComponents", MyComponents.GetType()); 
    this.Pipelines = (List<Pipeline>)info.GetValue("Pipelines", Pipelines.GetType()); 
} 

這就是所謂的反序列化構造,並且與任何構造,所述類的成員不被初始化,所以MyComponents.GetType()和不能使用Pipelines.GetType()(產生NRE)。

您可以使用這樣的事情,而不是

public Network(SerializationInfo info, StreamingContext context) 
{ 
    this.MyComponents = (List<Component>)info.GetValue("MyComponents", typeof(List<Component>)); 
    this.Pipelines = (List<Pipeline>)info.GetValue("Pipelines", typeof(List<Pipeline>)); 
} 
+0

嗯,這工作。我擺脫了錯誤。現在我正在加載保存的文件,並且它沒有實際加載。沒有什麼改變,我的清單仍然是空的。 – MonicaS

+0

嗯,你確定他們在保存時不是空的?也不會通過'catch {return new Network(); }'分支? –

+0

修正了這個問題。現在我得到這個mscorlib.dll中發生類型'System.Runtime.Serialization.SerializationException'的異常,但沒有在用戶代碼中處理 附加信息:未找到成員'ComponentBox'。 – MonicaS