我经常将它按顺序保存到具有非常简单的数据访问层的二进制文件中。您可以在这里使用几种方法,但我最喜欢这种方法,它相当简单而且速度很快。您甚至可以非常轻松地为文件中的条目创建索引表。
class Foo {
private int _someInteger;
private string _someString;
public virtual void Serialize(BinaryWriter writer) {
writer.Write(2); // A simple versioning, start at 0, then increment.
writer.Write(_someString);
writer.Write(_someInteger);
}
public virtual void Deserialize(BinaryReader reader) {
int version = reader.ReadInt32();
switch (version) {
case 2: // the string was only added in version 2 of the class serialization.
_someString = reader.ReadString();
goto case 1;
case 1: // continue at case 1.
_someInteger = reader.ReadInt32();
break; // break here, because version 0 was very different.
case 0: // in version 0 of the class there was actually a double, but it was always an integral number, so this basically is a conversion case.
_someInteger = (int)reader.ReadDouble();
break;
}
}
}
请注意按照与写入它们相同的顺序从文件中读取它们。
然后,您可以将其传递给流中的读取器和写入器,例如
Foo fooInstance = new Foo();
FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(fileStream);
fooInstance.Deserialize(reader);
它非常简单,而且您不必为愚蠢的 XML 序列化程序类公开所有字段和属性,因为它们总是给您带来问题。