如何使 C# 中的此类代码更短?

How to make this type of code in C# shorter?

嗨,我想缩短这段代码:

tb1n.Text = Settings2.Default.tb1n;
tb2n.Text = Settings2.Default.tb2n;
tb3n.Text = Settings2.Default.tb3n;
tb4n.Text = Settings2.Default.tb4n;
tb5n.Text = Settings2.Default.tb5n;
tb6n.Text = Settings2.Default.tb6n;
tb7n.Text = Settings2.Default.tb7n;
tb8n.Text = Settings2.Default.tb8n;
tb9n.Text = Settings2.Default.tb9n;
tb10n.Text = Settings2.Default.tb10n;
tb11n.Text = Settings2.Default.tb11n;
tb12n.Text = Settings2.Default.tb12n;
tb13n.Text = Settings2.Default.tb13n;

稍后我会添加更多设置来加载,我需要缩短它但我不知道如何。

我试图将这段代码变成这样的字符串:

int i = 1;
do
{
    string tbload = "tb" + i + "n.Text = Settings2.Default.tb" + i + "n";
    i++;
} while (i == 13);

但后来我意识到这不是好的解决方案,因为从字符串执行代码很难,我不喜欢它。

您可以创建可视树助手 class 并在视图中查找所有文本框实例。

帮手class:

public static class TreeHelper
    {
        public static IEnumerable<T> FindVisualChildren<T>(this DependencyObject depObj) where T : DependencyObject
        {
            if (depObj == null) yield break;

            for (var i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
            {
                var child = VisualTreeHelper.GetChild(depObj, i);
                var children = child as T;
                if (children != null)
                    yield return children;

                foreach (T childOfChild in FindVisualChildren<T>(child))
                    yield return childOfChild;
            }
        }
    }

通话

var children = this.FindVisualChildren<TextBox>();
foreach (var child in children)
{
   child.Text = Settings.Default[child.Name].ToString();
}

您可以将文本框和字符串存储在这样的列表中:

        List<TextBox> TextBoxes = new List<TextBox>() {
            tb1n,
            tb2n,
            tb3n,
            ...
        };

        List<string> mySettings = new List<string>(){
            Settings2.Default.tb1n,
            Settings2.Default.tb2n,
            Settings2.Default.tb3n,
            ...
        };

        foreach  (TextBox item in TextBoxes)
        {
            item.Text = mySettings[TextBoxes.FindIndex(a => a.Name == item.Name)];
        }

然后您可以使用 foreach 循环为每个 TextBox 赋予其文本 属性 值。