C# 唯一持久控制标识符
我们拥有的C# 唯一持久控制标识符,c#,winforms,configuration,uid,C#,Winforms,Configuration,Uid,我们拥有的 我们有一些复杂的winforms控件。为了存储它的状态,我们使用一些定制的序列化类。假设我们已经将其序列化为xml。现在,我们可以将此xml保存为用户目录中的文件,或将其包含在另一个文件中…… 但是 问题是, 如果用户在其winform应用程序中创建了几个这样的控件(在设计时),为了知道保存的配置中的哪个属于这些控件,最好使用哪个唯一标识符 因此,该标识符应: 在应用程序启动期间保持不变 自动给定(或者已经给定,就像我们可以假设控件名总是存在一样) 跨应用程序的唯一性 我认为人们
我们有一些复杂的winforms控件。为了存储它的状态,我们使用一些定制的序列化类。假设我们已经将其序列化为xml。现在,我们可以将此xml保存为用户目录中的文件,或将其包含在另一个文件中……
但是 问题是,
如果用户在其winform应用程序中创建了几个这样的控件(在设计时),为了知道保存的配置中的哪个属于这些控件,最好使用哪个唯一标识符 因此,该标识符应:
- 在应用程序启动期间保持不变
- 自动给定(或者已经给定,就像我们可以假设控件名总是存在一样)
- 跨应用程序的唯一性
用什么更好?为什么?我一直在使用一个由完整的控制层次结构树组成的复合标识符。假设您的表单名为Form1,那么您有一个groupbox Groupbox1和一个textbox TextBox1,复合标识符将是Form1/Groupbox1/TextBox1 如果您想遵循此操作,请参阅以下详细信息:
这种小型扩展方法可以实现以下功能:
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.\u flowLayoutPanel.label1”的内容
用法:
Control aaa;
Dictionary<string, ControlConfigs> configs;
...
configs[aaa.GetFullName()] = uniqueAaaConfig;
控制aaa;
词典配置;
...
配置[aaa.GetFullName()]=uniqueAaaConfig;
这是我最后创建的一个方法,它定义了一个唯一的名称,其中包括表单的全名(及其名称空间),然后是相关控件上方的每个父控件。所以它可能最终会是这样的:
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();
}