为什么我不能在C#中将对象序列化为二进制格式?

时间:2013-10-30 11:19:46

标签: c# serialization deserialization binaryformatter

我有这个函数将KnownNetowrks对象序列化为二进制格式:

const string FileNameBin = @".\knownnetworks.bin";

public static void SaveNetworksBin(KnownNetworks networks)
{
     Stream FileStream = File.Create(FileNameBin);
     BinaryFormatter serializer = new BinaryFormatter();
     serializer.Serialize(FileStream, networks);
     FileStream.Close();
}

KnownNetwork具有以下结构:

[Serializable]
public class KnownNetworks
{
    public static LinkedList<Network> List { get; private set; }

    public KnownNetworks()
    {
        if (List == null)
            List = new LinkedList<Network>();
    }

    ...

 }

班级网络也是[Serializable]

但是,当我调用函数SaveNetworksBin时,它总是保存一个大小为129字节的文件,即使参数networks有一个列表表示它已满或更低。因此,我认为LoadNetworksBin也不起作用。

public static KnownNetworks LoadNetworksBin()
{
    var result = new KnownNetworks();
    if (File.Exists(FileNameBin))
    {
        Stream FileStream = File.OpenRead(FileNameBin);
        BinaryFormatter deserializer = new BinaryFormatter();
        result = (KnownNetworks)deserializer.Deserialize(FileStream);
        FileStream.Close();
    }
    return result;
}

怎么了?我应该改变什么?

1 个答案:

答案 0 :(得分:3)

您的列表是静态的,因此不属于您要序列化的KnownNetworks实例。