5

我们有什么我们
有一些复杂的winforms控件。为了存储它的状态,我们使用了一些自定义的序列化类。假设我们已将其序列化为 xml。现在我们可以将此 xml 保存为用户目录中的文件或将其包含在另一个文件中......
但是......

问题是
如果用户在他的 winform 应用程序中创建了几个这样的控件(在设计时),为了知道哪些保存的配置属于这些控件中的哪一个,使用哪个唯一标识符更好?

所以这个标识符应该:

  • 在应用程序启动时保持不变
  • 自动给定(或已经给定,就像我们可以假设 Control.Name 始终存在)
  • 跨应用程序唯一

我认为人们可以想象几种方法来做到这一点,我相信可能会有一些默认的方法来做到这一点。

用什么比较好?为什么?

4

3 回答 3

2

这个小扩展方法可以完成工作:

public static class FormGetUniqueNameExtention
{
    public static string GetFullName(this Control control)
    {
        if(control.Parent == null) return control.Name;
        return control.Parent.GetFullName() + "." + control.Name;
    }
}

它返回类似'Form1._flowLayoutPanel.label1'的东西

用法:

Control aaa;
Dictionary<string, ControlConfigs> configs;
...
configs[aaa.GetFullName()] = uniqueAaaConfig;
于 2012-09-12T21:21:48.547 回答
1

我一直在使用由完整的控制层次结构树组成的复合标识符。假设您的表单名称是 Form1,那么您有一个组框 Groupbox1 和一个文本框 TextBox1,复合标识符将是 Form1/Groupbox1/TextBox1。

如果你想关注这个,这里有详细信息:

http://netpl.blogspot.com/2007/07/context-help-made-easy-revisited.html

于 2011-09-21T17:09:10.820 回答
1

这是我最终创建的方法,用于定义一个唯一名称,其中包括表单的全名(及其命名空间),然后是相关控件上方的每个父控件。所以它最终可能是这样的:

MyCompany.Inventory.SomeForm1.SomeUserControl1.SomeGroupBox1.someTextBox1

    static string GetUniqueName(Control c)
    {
        StringBuilder UniqueName = new StringBuilder();
        UniqueName.Append(c.Name);
        Form OwnerForm = c.FindForm();

        //Start with the controls immediate parent;
        Control Parent = c.Parent;
        while (Parent != null)
        {
            if (Parent != OwnerForm)
            {
                //Insert the parent control name to the beginning of the unique name
                UniqueName.Insert(0, Parent.Name + "."); 
            }
            else
            {
                //Insert the form name along with it's namespace to the beginning of the unique name
                UniqueName.Insert(0, OwnerForm.GetType() + "."); 
            }

            //Advance to the next parent level.
            Parent = Parent.Parent;
        }

        return UniqueName.ToString();
    }
于 2014-01-16T14:50:23.500 回答