首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在C#中寻找一个简单的独立持久字典实现

在C#中,一个简单的独立持久字典实现可以通过使用System.IOSystem.Runtime.Serialization.Formatters.Binary命名空间中的类来实现。以下是一个简单的示例:

代码语言:csharp
复制
using System;
using System.IO;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;

public class PersistentDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
    private string _filePath;

    public PersistentDictionary(string filePath)
    {
        _filePath = filePath;
        if (File.Exists(filePath))
        {
            Load();
        }
    }

    public void Load()
    {
        using (FileStream fs = new FileStream(_filePath, FileMode.Open))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            Dictionary<TKey, TValue> data = (Dictionary<TKey, TValue>)formatter.Deserialize(fs);
            foreach (KeyValuePair<TKey, TValue> kvp in data)
            {
                this[kvp.Key] = kvp.Value;
            }
        }
    }

    public void Save()
    {
        using (FileStream fs = new FileStream(_filePath, FileMode.Create))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(fs, this);
        }
    }
}

这个PersistentDictionary类继承自Dictionary<TKey, TValue>,并添加了LoadSave方法,用于将字典数据保存到文件中并从文件中加载数据。

使用方法如下:

代码语言:csharp
复制
var dict = new PersistentDictionary<string, int>("data.bin");
dict["apple"] = 5;
dict["banana"] = 3;
dict.Save();

在这个示例中,我们创建了一个PersistentDictionary对象,并添加了两个键值对,然后调用Save方法将字典数据保存到文件data.bin中。

下次启动程序时,我们可以使用Load方法从文件中加载数据:

代码语言:csharp
复制
var dict = new PersistentDictionary<string, int>("data.bin");
dict.Load();
foreach (var item in dict)
{
    Console.WriteLine($"{item.Key}: {item.Value}");
}

这样,我们就可以实现一个简单的独立持久字典。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券