里克·戈夫
新成员
- 已加入
- 2021年1月23日
- 留言内容
- 2
- 编程经验
- Beginner
我不确定我是否使用任何正确的语言,而且我是初学者...
我像这样创建了一个ObservableDictionary:
我需要能够以不可读的二进制格式将其保存到文件中,并在程序的下一次加载时恢复...
这些是我使用过的方法,但是我无法使它们起作用...
请帮助我...提前谢谢。
我像这样创建了一个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);
}
}
请帮助我...提前谢谢。