如何序列化和反序列化从面板内部收集的用户输入?

How to serialize & deserialize user inputs gathered from inside a panel?

我正在创建一个 winforms 应用程序,让用户在不同的面板中进行输入。我已经编写了一种遍历面板并从不同控件获取输入的方法。现在我需要找到一种方法来序列化这些输入并在以后反序列化它们,以便所有输入再次位于正确的控件中(例如 "Jack" 再次位于文本框 "tbName" 中)。

我想到了多种解决方案,例如为每个面板创建一个列表,该列表序列化为结构类似于 "tbName=Jack" 的 .txt 等等。但我真的不知道如何在不再次遍历面板控件和列表的情况下反序列化它。或者我可以将整个 Panel 对象与子控件一起序列化吗?

//This is the method I use to gather the inputs from the panels.

public IEnumerable<Control> GetControls(Control parentControl)
    {
        foreach (Control child in parentControl.Controls)
            {
                yield return child;
                foreach (Control controlChild in GetControls(child))
                {
                    yield return controlChild;
                }
            }
        }

不建议序列化整个表单,因为它有很多您不需要的信息(这可能会影响性能)。相反,创建一个单独的 class,使其成为 [Serializable()],创建存储信息所需的所有变量,并序列化 class.

编辑:

假设您有以下形式:

namespace Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // here, you create the serializing and deserializing methods
        public void SerializingInfo()
        {
            // done however you see fit
        }

        public StorageClass DeserializingInfo()
        {
            // also done however you see fit
        }
    }
}

然后,将另一个 class 添加到您的项目中,在我的示例中,它被命名为 StorageClass。 这看起来像:

namespace Test
{
    [Serializable()]
    public class StorageClass
    {
        // has all your properties
    }
}

然后,无论您需要存储什么,都可以通过 setting/getting Form1 中的属性来实现。当你序列化它时,所有的属性都被一起序列化,你可以通过访问它们在 DeserializeInfo().

中的 getter 方法来检索它

对于数量有限的控件,您只需在项目中创建设置 --> 每个控件的属性:

然后,在控件的 ApplicationSettings 属性 中,单击 PropertyBinding 右侧的三个点...

...和 ​​select 文本条目的设置:

您现在将拥有:

最后,在窗体的FormClosing()事件中,保存设置:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    Properties.Settings.Default.Save();
}

感谢您的回答,两者都是正确且有效的,但最后我想出了自己的解决方案: 我用我需要的所有属性制作了一个单独的 class,就像 @krobelusmeetsyndra 建议的那样,并制作了我刚刚制作的 class 对象的通用列表。然后我遍历控件(使用我问题中的方法),将数据放入列表中并使用 XmlSerializer 序列化该数据。 与反序列化相同:我制作了一个我自己的对象类型的列表,然后从该列表中的 XML 加载数据,然后将其分配给正确的控件。

希望对遇到同样问题的大家有所帮助!