2015-12-28 3 views
0

Я пытаюсь сохранить и загрузить в C# с сериализацией. Однако у меня возникают проблемы с загрузкой, и я не уверен, что понимаю, в чем проблема. Вот код:Deserialize C# with BinaryFormatter

[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

Исправлено. Теперь я получаю это Исключение типа «System.Runtime.Serialization.SerializationException» произошло в mscorlib.dll, но не обрабатывалось в коде пользователя Дополнительная информация: Member 'ComponentBox' не найден. – MonicaS