使用 BinaryFormatter 反序列化 c#

Deserialize c# with 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.

谢谢!

问题就在这里

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

这就是所谓的反序列化构造函数,与任何构造函数一样,class 的成员未初始化,因此无法使用 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>));
}