Вы должны создать экземпляр класса List<>
, прежде чем сможете его использовать. Вы создаете класс stad
, но свойства City
и Temperature
нигде не создаются.
Попробуйте это:
class stad {
public List<string> City { get; } = new List<string>();
public List<double> Temperature { get; } = new List<double>();
}
Он будет уверен, что если вы создайте экземпляр stad
, он также создаст город и температуру.
Обновление:
Я бы go для City
класса, который содержит город название и температура. Таким образом, вы храните связанную информацию вместе.
Например:
public class CityWithTemperature
{
public string CityName {get; set; }
public double Temperature {get; set; }
}
public static void Main(string[] args)
{
// declare a list which could contain CityWithTemperature classes
var cityTemperatures = new List<CityWithTemperature>();
// Create the first city
var firstCity = new CityWithTemperature();
firstCity.CityName = "New York";
firstCity.Temperature = 18.4;
cityTemperatures.Add(firstCity);
// create the second city
// you could also write it shorter:
cityTemperatures.Add( new CityWithTemperature
{
CityName = "Houston",
Temperature = 10.4
});
// display them
foreach(var cityInfo in cityTemperatures)
{
Console.WriteLine($"{cityInfo.CityName} with a temperature of {cityInfo.Temperature}");
}
// or a for loop:
for(int i=0;i<cityTemperatures.Count;i++)
{
Console.WriteLine($"{cityTemperatures[i].CityName} with a temperature of {cityTemperatures[i].Temperature}");
}
}