解决  如何将自定义ObservableDictionary保存到文件,并在以后还原?

已加入
2021年1月23日
留言内容
2
编程经验
Beginner
我不确定我是否使用任何正确的语言,而且我是初学者...

我像这样创建了一个ObservableDictionary:

ObservableDictionary.cs:
[Serializable]
    public class ObservableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, INotifyCollectionChanged
    {
        public ObservableDictionary() : base() { }
        public ObservableDictionary(int capacity) : base(capacity) { }
        public ObservableDictionary(IEqualityComparer<TKey> comparer) : base(comparer) { }
        public ObservableDictionary(IDictionary<TKey, TValue> dictionary) : base(dictionary) { }
        public ObservableDictionary(int capacity, IEqualityComparer<TKey> comparer) : base(capacity, comparer) { }
        public ObservableDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) : base(dictionary, comparer) { }

        public event NotifyCollectionChangedEventHandler CollectionChanged;

        public new TValue this[TKey key]
        {
            get
            {
                return base[key];
            }
            set
            {
                OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, key, 0));
                base[key] = value;
            }
        }

        public new void Add(TKey key, TValue value)
        {
            base.Add(key, value);
            Storage.Save(this, "./cache.txt", false);
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, key, 0));
        }

        public new bool Remove(TKey key)
        {
            bool x = base.Remove(key);
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, key, 0));
            return x;
        }

        public new void Clear()
        {
            base.Clear();
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        }


        protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            if (CollectionChanged != null)
            {
                CollectionChanged(this, e);
            }
        }
    }

我需要能够以不可读的二进制格式将其保存到文件中,并在程序的下一次加载时恢复...

这些是我使用过的方法,但是我无法使它们起作用...

Storage.cs:
public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
        {
            using Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create);
            var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            binaryFormatter.Serialize(stream, objectToWrite);
        }
        
public static ObservableDictionary<> ReadFromBinaryFile<T>(string filePath)
        {
            using (Stream stream = File.Open(filePath, FileMode.Open))
            {
                var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                return (T)binaryFormatter.Deserialize(stream);
            }
        }

请帮助我...提前谢谢。
 

跳伞

工作人员
已加入
2019年4月6日
留言内容
2,463
位置
弗吉尼亚州切萨皮克
编程经验
10+
您在上面发布的内容有两点突出。

您不能只附加到包含序列化数据的现有文件,然后期望解串器找到旧数据和新附加的数据,然后以某种方式使解串器将两个数据块组合在一起。

ReadeFromBinaryFile<T>() should return an object of type T (based on your line 13). It should not return a generic ObservableDictionary<> like you declared on line 8. Furthermore it would make better sense (and seem symmetrical) that if you called WriteToBinaryFile<MyObjectType>("myfille.bin", myObject); that you later call MyObjectType myObject = ReadFromBinaryFile<MyObjectType>("myfile.bin");

It doesn't really make sense to serialize an ObservervableDictionary because "observable" implies that there maybe various other objects which are listening to the CollectionChanged event of the object. Are you realistically going to be able to save the list of those other objects during 序列化, and then when you deserialize hook up the event handlers for those other objects again? 什么 happens when you serialize now, restart the computer, then re-run the program and deserialize? There is no guarantee that the program will reload into the same memory addresses, nor that the objects allocated within the program will have the same memory addresses/offsets. A Dictionary<TKey, TValue> is already serializable on its own. There is no need to make a serializable 可观察的 dictionary.
 
最佳 底部