在变量名中使用i

时间:2016-03-16 19:47:34

标签: c#

所以我有这种代码(我为XAML元素赋值 ),这对于" for"循环。

Day1d.Text = string.Format("{0:dd/MM}", DateTime.Today.AddDays(1));
Day2d.Text = string.Format("{0:dd/MM}", DateTime.Today.AddDays(2));
Day3d.Text = string.Format("{0:dd/MM}", DateTime.Today.AddDays(3));
Day4d.Text = string.Format("{0:dd/MM}", DateTime.Today.AddDays(4));

Day1t.Text = "°" + (myWeatherForecast.forecastlist[1].temp).ToString();
Day2t.Text = "°" + (myWeatherForecast.forecastlist[2].temp).ToString();
Day3t.Text = "°" + (myWeatherForecast.forecastlist[3].temp).ToString();
Day4t.Text = "°" + (myWeatherForecast.forecastlist[4].temp).ToString();

但是我所有尝试包括"我"变量名失败了。有没有办法实现这个目标?

3 个答案:

答案 0 :(得分:1)

您可以创建一个迭代实例的循环:

int counter = 1; // are you sure it shouldn't start at 0?
foreach (TextBox tb in new TextBox[] { Day1d, Day2d, Day3d, Day4d })
{
    tb.Text = string.Format("{0:dd/MM}", DateTime.Today.AddDays(counter));

    counter++;
}

counter = 1;
foreach (TextBox tb in new TextBox[] { Day1t, Day2t, Day3t, Day4t })
{
    tb.Text = "°" + (myWeatherForecast.forecastlist[counter].temp).ToString();

    counter++;
}

答案 1 :(得分:0)

您无法使用其他变量撰写变量的名称。这样做的方法是创建一个List,然后迭代该List

var textBoxes1 = new List<TextBox> { Day1d, Day2d, Day3d, Day4d }
var textBoxes2 = new List<TextBox> { Day1t, Day2t, Day3t, Day4t }
foreach (var textbox in textBoxes1)
{
    var index = textBoxes1.IndexOf(textBox) + 1;
    textbox.Text = string.Format("{0:dd/MM}", DateTime.Today.AddDays(index));
}
foreach (var textbox in textBoxes2)
{
    var index = textBoxes2.IndexOf(textBox) + 1;
    textbox.Text = "°" + (myWeatherForecast.forecastlist[index].temp).ToString();
}

注意:您可以通过不同方式解决此问题:

  • 使用数组而不是列表
  • 保留自己的计数器,而不是做IndexOf
  • 使用for循环,而不是foreach

哪个更好是主要基于意见(虽然我的方法不是最快的,但如果你只有4个项目则没有关系)

答案 2 :(得分:0)

假设您使用的是WPF,则可以使用FindName

尝试:

for (int i = 1; i < 5; i++)
{
     ((TextBox)this.FindName("Day" + i + "d")).Text = string.Format("{0:dd/MM}", DateTime.Today.AddDays(i));
     ((TextBox)this.FindName("Day" + i + "t")).Text = "°" + (myWeatherForecast.forecastlist[i].temp).ToString();
}