gpt4 book ai didi

C# - 保存程序的变量

转载 作者:太空宇宙 更新时间:2023-11-03 18:09:12 24 4
gpt4 key购买 nike

我现在正在用 C# 制作游戏(这是一个控制台应用程序)并且需要保存它的变量。

我试过使用设置,但有一个大问题:如果更改文件名或将文件转移到其他地方,设置就会丢失。

那么什么是设置的一个很好的替代方案来保存变量并稍后在应用程序中检索它们?

编辑:我想将变量保存到文本文件中并稍后检索它,这可能吗?如果是,那么如何?

并且请不要推荐在线服务器,因为我正在开发一款单人游戏,而不会跟踪任何玩家。

最佳答案

存储固定类型数据的一种简单方法是使用 BinaryFormatter 类进行序列化。

参见 MSDN documentation for Binary Formatter .我在这里复制了一些相关代码。

using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

void SaveData()
{
// Create a hashtable of values that will eventually be serialized.
Hashtable addresses = new Hashtable();
addresses.Add("Jeff", "123 Main Street, Redmond, WA 98052");
addresses.Add("Fred", "987 Pine Road, Phila., PA 19116");
addresses.Add("Mary", "PO Box 112233, Palo Alto, CA 94301");

// To serialize the hashtable and its key/value pairs,
// you must first open a stream for writing.
// In this case, use a file stream.
FileStream fs = new FileStream("DataFile.dat", FileMode.Create);

// Construct a BinaryFormatter and use it to serialize the data to the stream.
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, addresses);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to serialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}
}


void LoadData()
{
// Declare the hashtable reference.
Hashtable addresses = null;

// Open the file containing the data that you want to deserialize.
FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
try
{
BinaryFormatter formatter = new BinaryFormatter();

// Deserialize the hashtable from the file and
// assign the reference to the local variable.
addresses = (Hashtable) formatter.Deserialize(fs);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}

// To prove that the table deserialized correctly,
// display the key/value pairs.
foreach (DictionaryEntry de in addresses)
{
Console.WriteLine("{0} lives at {1}.", de.Key, de.Value);
}
}

关于C# - 保存程序的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19841182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com