繁体   English   中英

使用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());
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM