如何订购应用程序设置
How to order application settings
每当我的 C# 项目中需要新的应用程序设置时,我都会通过 PROJECT -> Properties -> Settings 添加它。目前我的 C# 项目中有大约 20 个应用程序设置,但它们是乱序的。
为了能够在运行时更改设置,我通过遍历设置创建了一个简单的设置面板。
foreach (System.Configuration.SettingsProperty prop in Properties.Settings.Default.Properties)
{
Label caption = new Label();
caption.Text = prop.Name;
caption.Location = new Point(10, this.Height - 70);
caption.Size = new Size(100, 13);
caption.Anchor = AnchorStyles.Left | AnchorStyles.Top;
TextBox textbox = new TextBox();
textbox.Name = prop.Name;
textbox.Text = Properties.Settings.Default[prop.Name].ToString();
textbox.Location = new Point(120, this.Height - 70);
textbox.Size = new Size(this.Width - 140, 23);
textbox.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
if (prop.IsReadOnly)
textbox.ReadOnly = true;
this.Height += 30;
this.Controls.Add(caption);
this.Controls.Add(textbox);
}
它工作正常。但是标签的顺序与我在 Visual Studio UI.
中输入的顺序不合逻辑
有没有办法在运行时重新排列 Visual Studio 中的设置顺序或对 System.Configuration.SettingsPropertyCollection 进行排序?
因为 SettingsPropertyCollection 是一个 IEnumerable,所以我试图像这样使用 LINQ:
Properties.Settings.Default.Properties.OrderBy(s => s.Name)
但它没有编译,抱怨缺少 SettingsPropertyCollection 的 OrderBy 扩展。
你可以试试:
Properties.Settings.Default.Properties.OfType<SettingsProperty>().OrderBy(s => s.Name)
由于它实现了 IEnumerable
而不是 IEnumerable<T>
,因此您需要在调用 OrderBy
之前先调用 Cast<T>
:
Properties.Settings
.Default
.Properties
.Cast<System.Configuration.SettingsProperty>()
.OrderBy(s => s.Name)
每当我的 C# 项目中需要新的应用程序设置时,我都会通过 PROJECT -> Properties -> Settings 添加它。目前我的 C# 项目中有大约 20 个应用程序设置,但它们是乱序的。
为了能够在运行时更改设置,我通过遍历设置创建了一个简单的设置面板。
foreach (System.Configuration.SettingsProperty prop in Properties.Settings.Default.Properties)
{
Label caption = new Label();
caption.Text = prop.Name;
caption.Location = new Point(10, this.Height - 70);
caption.Size = new Size(100, 13);
caption.Anchor = AnchorStyles.Left | AnchorStyles.Top;
TextBox textbox = new TextBox();
textbox.Name = prop.Name;
textbox.Text = Properties.Settings.Default[prop.Name].ToString();
textbox.Location = new Point(120, this.Height - 70);
textbox.Size = new Size(this.Width - 140, 23);
textbox.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
if (prop.IsReadOnly)
textbox.ReadOnly = true;
this.Height += 30;
this.Controls.Add(caption);
this.Controls.Add(textbox);
}
它工作正常。但是标签的顺序与我在 Visual Studio UI.
中输入的顺序不合逻辑有没有办法在运行时重新排列 Visual Studio 中的设置顺序或对 System.Configuration.SettingsPropertyCollection 进行排序?
因为 SettingsPropertyCollection 是一个 IEnumerable,所以我试图像这样使用 LINQ:
Properties.Settings.Default.Properties.OrderBy(s => s.Name)
但它没有编译,抱怨缺少 SettingsPropertyCollection 的 OrderBy 扩展。
你可以试试:
Properties.Settings.Default.Properties.OfType<SettingsProperty>().OrderBy(s => s.Name)
由于它实现了 IEnumerable
而不是 IEnumerable<T>
,因此您需要在调用 OrderBy
之前先调用 Cast<T>
:
Properties.Settings
.Default
.Properties
.Cast<System.Configuration.SettingsProperty>()
.OrderBy(s => s.Name)