这会导致运行时出现序列化异常。这只是一个演示项目,用于测试执行此操作的最佳方法。我包括了主要方法和我试图序列化的类。
忽略:我真的不能添加更多细节,我已经描述了问题,附上了代码,这个“请添加更多细节”的事情是有史以来最愚蠢的事情。让我已经发布它。
Data toSend = new Data();
toSend.Output();
///SERIALIZE
BinaryFormatter formatter = new BinaryFormatter();
Stream streamOut = File.OpenWrite("file");
formatter.Serialize(streamOut, toSend);
streamOut.Close();
Console.WriteLine("----------------------------");
///DESERIALIZE
Stream streamIn = File.OpenRead("file");
Object received = formatter.Deserialize(streamIn);
Data toReceive = (Data)received;
toReceive.Output();
class Data : ISerializable
{
int integerData;
string stringData;
bool booleanData;
int shouldnotbeserialized;
public Data()
{
integerData = 1;
stringData = "Hello";
booleanData = true;
shouldnotbeserialized = 55;
}
//To deserialize
public Data(SerializationInfo info, StreamingContext context)
{
integerData = info.GetInt32("theint");
stringData = info.GetString("thestring");
booleanData = info.GetBoolean("thebool");
}
public void Output()
{
Console.WriteLine(integerData);
Console.WriteLine(stringData);
Console.WriteLine(booleanData);
Console.WriteLine(shouldnotbeserialized);
}
//Implemented method to serialize
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("thestring", stringData);
info.AddValue("theint", integerData);
info.AddValue("thebool", booleanData);
}
}
异常消息:
在程序集“SerializationDemo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”中键入“SerializationDemo.Data”未标记为可序列化。