C# - 保存程序的变量

标签 c# variables save

我现在正在用 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/

相关文章:

c# - 理解和解决 K-Way 归并排序

javascript - 如何创建一个将属性值分配给其他属性的函数?

android - 在 react-native 中从 java 代码访问 java 变量到 javascript 代码

java - 从上次中断的地方继续?

c# - Exchange Web 服务 : More Complex SearchFilters

c# - 运算符 '&&' 不能应用于类型 'lambda expression' 和 'lambda 表达式的操作数

python - 如何在Tensorflow中使用变量的旧值和新值?

c++ - 使用自定义扩展名保存文件

ios - 接收 NSUserDefault 时崩溃(保存数据)

c# - 从 System.Web.UI.UserControl 基类继承