使用BinaryFormatter反序列化c#

时间:2015-12-28 20:01:22

标签: c# serialization deserialization 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.

谢谢!

1 个答案:

答案 0 :(得分: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>));
}