【发布时间】:2019-07-17 11:30:32
【问题描述】:
当我停止并重新启动程序时,我有一个标志类(以及一个更改标志值的简单按钮)我想查看更改后的布尔变量。我对它进行了搜索,但我有点迷路了。 现在我有一个构造函数,但我不知道如何将它与保存/加载函数一起使用。
最简单的方法是什么?
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.Collections; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization; using System.Xml.Serialization; using System.Xml;
namespace SaveReloadDeneme
{
[Serializable]
public partial class Form1 : Form
{
bool flag;
bool flag2;
public Form1()
{
InitializeComponent();
flag = false;
flag2 = false;
}
private void Button1_Click(object sender, EventArgs e)
{
flag = true;
flag2 = true;
Console.WriteLine("Flag changed: " + flag);
Console.WriteLine("Flag2 changed: " + flag2);
}
void SaveData()
{
// Create a hashtable of values that will eventually be serialized.
Hashtable addresses = new Hashtable();
addresses.Add(1, flag);
// 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();
}
}
public 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();
}
}
private void Button2_Click(object sender, EventArgs e)
{
}
}
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
Form1 f = new Form1();
f.SaveData();
f.LoadData();
}
当我打开 ".dat" 文件时,它是乱码,我认为不包含当前保存的标志值。
【问题讨论】:
-
我建议使用 JSON。它简单易懂,并且具有相当的人类可读性。
-
@mjwills 好的,我会尝试使用 JSON
-
看你的代码,可能不是序列化问题,而是对你程序的初始化工作原理的误解。
标签: c# serialization boolean deserialization