假设我们有 1000 个字符串或对象的列表,将其序列化到文件中,下次想要更新其中一个并再次序列化。
当前场景:序列化 1000 个项目。反序列化所有这些更新元素之一,然后再次序列化所有 1000 个元素。我们不需要保存\加载所有项目来更新一个元素,这是一种更好的方法吗?
更新
我的所有数据都在列表 itemTosave 的实例中。下面的类序列化 itemTosave。
[System.Serializable]
internal sealed class SaveAndLoadContainer : ISerializable {
private List<SaveAndLoadItem> loadedItems;
public static SaveAndLoadContainer Instance_Save;
public static SaveAndLoadContainer Instance_Load;
private List<SaveAndLoadItem> loadedItems;
public List<SaveAndLoadItem> LoadedItems {
get {
return this.loadedItems;
}
}
public SaveAndLoadContainer(){
Instance_Save = this;
}
private SaveAndLoadContainer(SerializationInfo info, StreamingContext contex){
loadedItems = (List<SaveAndLoadItem>)info.GetValue("UnsavedItems", typeof(List<SaveAndLoadItem>));
SaveAndLoadManager.ItemsToSave.Clear();
SaveAndLoadManager.ItemsToSave.TrimExcess();)
SaveAndLoadManager.ItemsToSave.AddRange(loadedItems);
}
public void GetObjectData (SerializationInfo info, StreamingContext context){
List<SaveAndLoadItem> unsavedItems = SaveAndLoadManager.ItemsToSave;
info.AddValue("UnsavedItems", unsavedItems, typeof(List<SaveAndLoadItem>));
}
}
SaveAndLoadItem 类是:
[System.Serializable]
internal sealed class SaveAndLoadItem {
public SaveAndLoadItem(){
UniqueName = "--Nothing--";
Value = null;
ValueType = null;
IsClient = false;
}
public SaveAndLoadItem(string uniqueName, object value,Type typeOfValue,bool isClient){
UniqueName = uniqueName;
Value = value;
ValueType = typeOfValue;
IsClient = isClient;
}
public string UniqueName;
public System.Object Value;
public Type ValueType;
public bool IsClient;
}