独特的持久控制标识符

6

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

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

因此,此标识符应满足以下条件:

  • 在应用程序启动时保持不变
  • 自动分配(或已经分配,例如我们可以假设Control.Name始终存在)
  • 在应用程序中唯一

我认为可以想象几种方法来实现它,我相信可能有一些默认的方法。

使用什么方法比较好?为什么?

3个回答

4
这个小的扩展方法可以完成工作:
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;

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();
    }

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接