反序列化一些类

时间:2019-05-18 14:29:23

标签: c# binaryformatter

我创建了一个可序列化的类,在对这些文件进行反序列化后,在对一些类实例进行序列化后,我得到了一个类,但是我需要获取所有类。

我使用BinaryFormatter序列化类。我使用.NET Framework在C#上进行编码。

我现在反序列化:

using (var fs = new FileStream("doing.dat", FileMode.OpenOrCreate))
{
    ActionsClass = formatter.Deserialize(fs) as Doing;
    items.Add(ActionsClass.action);
}

课堂活动:

[Serializable]
public class Doing : ActionsForm
{
    public Doing(DateTime leadtime, string act)
    {
        if (leadtime < DateTime.Now) throw new ArgumentException("Some error text", nameof(leadtime));
        if (act == "") throw new ArgumentException("Some error text", nameof(act));
        PostTime = DateTime.Now;
        TimeLead = leadtime;
        action = act;
    }
}

以及ActionsForm类:

[Serializable]
public abstract class ActionsForm
{
    public DateTime PostTime { get; protected set; }
    public DateTime TimeLead { get; protected set; }
    public string action { get; protected set; }
}

1 个答案:

答案 0 :(得分:0)

您必须反序列化序列化对象的时间。

BinaryFormatter formatter = new BinaryFormatter();

DerivedClass object1 = new DerivedClass() { _baseField = "Object 1" };
DerivedClass object2 = new DerivedClass() { _baseField = "Object 2" };

using (FileStream writestream = new FileStream(@"data.bin", FileMode.Create, FileAccess.Write))
{
    formatter.Serialize(writestream, object1);
    formatter.Serialize(writestream, object2);
}

FileStream readstream = new FileStream(@"data.bin", FileMode.Open, FileAccess.Read);

DerivedClass deserializedobject1 = (DerivedClass)formatter.Deserialize(readstream);
DerivedClass deserializedobject2 = (DerivedClass)formatter.Deserialize(readstream);

readstream.Dispose();