【问题标题】:How to save changes to a variable? [duplicate]如何保存对变量的更改? [复制]
【发布时间】:2015-06-16 02:33:19
【问题描述】:

我想问你是否有人知道我如何保存程序中的更改,以便在重新启动时,更改会保留?

例如,我有一个布尔变量,其默认值为“false”。 我想在初始启动后,将值更改为“true”,这样当我关闭并启动程序时,布尔变量值将为 true。

【问题讨论】:

标签: c# wpf


【解决方案1】:

选择要用于持久化数据的格式。在应用程序启动时 - 读取文件并将其反序列化为您的模型。关闭时 - 将其序列化并保存到文件。看下一个问题:Best practice to save application settings in a Windows Forms Application

下一个样本取自上述链接:

using System;
using System.IO;
using System.Web.Script.Serialization;

namespace MiscConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            MySettings settings = MySettings.Load();
            Console.WriteLine("Current value of 'myInteger': " + settings.myInteger);
            Console.WriteLine("Incrementing 'myInteger'...");
            settings.myInteger++;
            Console.WriteLine("Saving settings...");
            settings.Save();
            Console.WriteLine("Done.");
            Console.ReadKey();
        }

        class MySettings : AppSettings<MySettings>
        {
            public string myString = "Hello World";
            public int myInteger = 1;
        }
    }

    public class AppSettings<T> where T : new()
    {
        private const string DEFAULT_FILENAME = "settings.jsn";

        public void Save(string fileName = DEFAULT_FILENAME)
        {
            File.WriteAllText(fileName, (new JavaScriptSerializer()).Serialize(this));
        }

        public static void Save(T pSettings, string fileName = DEFAULT_FILENAME)
        {
            File.WriteAllText(fileName, (new JavaScriptSerializer()).Serialize(pSettings));
        }

        public static T Load(string fileName = DEFAULT_FILENAME)
        {
            T t = new T();
            if(File.Exists(fileName))
                t = (new JavaScriptSerializer()).Deserialize<T>(File.ReadAllText(fileName));
            return t;
        }
    }
}

【讨论】:

    【解决方案2】:

    这就是我们拥有的数据库......

    或配置文件

    或文件系统

    你需要保留数据,它不能在内存中它必须在磁盘上

    了解各种数据持久化策略,尝试一下,如果您遇到困难,请告诉我们

    【讨论】:

      猜你喜欢
      • 2021-05-15
      • 2019-12-17
      • 1970-01-01
      • 2013-09-16
      • 1970-01-01
      • 2016-10-03
      • 2017-11-29
      • 1970-01-01
      • 2012-04-17
      相关资源
      最近更新 更多