C#中的Dictionaries——键/值的永久性

本文关键字:永久性 中的 Dictionaries | 更新日期: 2023-09-27 18:20:04

我可以在代码中永远保留C#代码中的键/项吗?:

class Program
{
    public class Variable
    {
        public object Value { get; set; }
    }
    static void Main(string[] args)
    {
        Console.WriteLine("Hi, please log in...");
        Console.WriteLine("Enter your username: ");
        string y = Console.ReadLine();
        Console.WriteLine("Enter your passcode: ");
        string n = Console.ReadLine();
        Dictionary<String, String> usersDict = new Dictionary<String, String>();
        bool exists = usersDict.ContainsKey("n") ? usersDict["n"] == "y" : false;
        if (exists == true)
        { 
            Console.WriteLine("Hello; "+y);
            Console.ReadLine();
        }
        else
        {
            usersDict.Add(n, y);

            Console.WriteLine("You have been added: " + y);
            Console.ReadLine();
        }
    }
}

所以有人可以创建一个帐户,然后改天登录??非常感谢您的帮助!

C#中的Dictionaries——键/值的永久性

DataTable是Dictionary的一个很好的替代品,因为DataTable有方便的ReadXML和WriteXML方法,可以将它们的数据写入XML格式的文件。

以下是一种将Dictionary加载到DataTable并将其写入文件的方法:

void WriteDictionaryToFile(Dictionary<string, string> dict, string filename)
    {
        using (DataTable dt = new DataTable("Dict"))
        {
            dt.Columns.Add("Key", typeof(string));
            dt.Columns.Add("Value", typeof(string));
            foreach (var kvp in dict)
            {
                dt.Rows.Add(kvp.Key, kvp.Value);
            }
            dt.WriteXml(filename);
        }
    }

一种从文件中读取字典的方法:

void ReadDictionaryFromFile(Dictionary<string, string> dict, string filename)
{
    DataTable dt = new DataTable("Dict");
    dt.Columns.Add("Key", typeof(string));
    dt.Columns.Add("Value", typeof(string));
    dt.ReadXml(filename);
    foreach (DataRow row in dt.Rows)
    {
        dict[row[0].ToString()] = row[1].ToString();
    }
}

这些方法肯定需要添加一些异常处理。

您还可以通过使用类型参数代替"字符串"来使这些方法具有通用性。例如:

void ReadDictionaryFromFile<T,U>(Dictionary<T, U> dict, string filename)
{
    DataTable dt = new DataTable("Dict");
    dt.Columns.Add("Key", typeof(T));
    dt.Columns.Add("Value", typeof(U));
    dt.ReadXml(filename);
    foreach (DataRow row in dt.Rows)
    {
        dict[(T)row[0]] = (U)row[1];
    }
}

问题的简短答案不是你目前是如何设置的。

目前,一旦程序完成main函数,main的堆栈帧将被释放,导致所有内存被释放。这适用于您运行的所有程序。

为了解决这个问题,您需要设置一个非易失性文件或存储系统(文本文件、XML文档、数据库等),以将您想要保存的数据保存在程序外部。

为了简单起见,我建议你坚持使用文本文件,直到你能了解更多关于IO的信息

这些链接应该给你一个起点:

MSDN:如何:写入文本文件

MSDN:如何:从文本文件读取

如果您只想存储字典并在需要时将其检索回来,那么您可以使用JSON序列化/反序列化来完成此操作。我使用了下面的Newtonsoft JSON(也可以通过Nuget获得)库来序列化/反序列化。

Dictionary<string, string> myDictionary = new Dictionary<string, string> { { "1", "A" }, { "2", "B" } };
//Serialize Dictionary to string and store in file
string json = Newtonsoft.Json.JsonConvert.SerializeObject(myDictionary);
System.IO.File.WriteAllText(@"C:'Docs'json.txt", json);
//Read serialized dictionary json string and Deserialize to Dictionary object
string jsonString = System.IO.File.ReadAllText(@"C:'Docs'json.txt");
Dictionary<string, string> deserializedDictionary = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonString);

希望这能帮助你。。。