问题描述:

So I have this kind of code (I'm assigning values to XAML elements

), which begs for a "for" loop.

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

But all my attempts to include "i" in variable name failed miserably. Is there a way to achieve this?

网友答案:

You can create a loop where you iterate over the instances:

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++;
}
网友答案:

You can't compose the name of the variable using another variable. The way to do this would be to create a List and then iterate over that 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();
}

NOTE: You can solve this in different ways:

  • using arrays instead of lists
  • keeping your own counter, instead of doing IndexOf
  • using a for loop, instead of a foreach

Which one is better is mostly based on opinion (although my method is not the fastest, but it doesn't matter if you only have 4 items)

网友答案:

You can use FindName assuming you are using WPF.

Try:

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();
}
相关阅读:
Top