這會在運行時導致序列化異常。這只是一個演示項目來測試這樣做的最佳方式。我包括了主要的方法和即將嘗試序列化的類。我在序列化時犯了什麼錯誤?
忽略:我真的無法添加更多的細節,我已經描述了這個問題,附上代碼,這個「請添加更多細節」的東西是有史以來最愚蠢的事情。我已經發布了。
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.Data' 'SerializationDemo, 版本= 1.0.0.0,文化=中性公鑰=空' 未標記 爲可序列化。
@walther在程序集'SerializationDemo,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null'中鍵入'SerializationDemo.Data'未被標記爲可序列化。 – Innkeeper 2013-04-20 14:17:26
等等......這是否意味着我還需要[]屬性?不是從界面派生出來的嗎? – Innkeeper 2013-04-20 14:18:32
'[Serializable]'是你需要的 – IAbstract 2013-04-20 14:18:58