对于大多数人(熟练的程序员)来说,标题可能听起来不太好,但是我在学习C#基础知识的第三周,我无法弄清楚如何解决下一个任务。 我将为一堆城市储存一些温度,首先要求用户输入cityName,然后再输入该城市的实际温度。所有这些东西都应该保存在列表<>中,我将使用Class和Constructor。 当我尝试打印出结果(使用的foreach),它打印出我的名字空间的名字和我的课,如“Task_5.City” 请告诉我错我的代码名称:为什么写入项目到控制台只写入命名空间和类名而不是数据?
public class City //class
{
public string CityName { get; set; }
public int Temperature { get; set; }
public City(string name, int temp)//konstruktor
{
this.CityName = name;
this.Temperature = temp;
}
}
class Program
{
static void Main(string[] args)
{
var cityList = new List<City>();
Console.WriteLine("What is your city?");
string cityName = Console.ReadLine();
Console.WriteLine("What temperature for this city?");
int temp = Convert.ToInt32(Console.ReadLine());
City myCity = new City(cityName, temp);
cityList.Add(myCity);
foreach (var item in cityList)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
'但是在这里,你只能得到一个城市和温度并且只能打印它。为什么在这种情况下需要一个列表?' - 这完全不相关,但让我帮忙回答:因为该代码要么显然是在进行中,要么被削减以缩小规模。将第二个城市添加到该列表非常容易,它仍然无法按预期工作。此外,OP明确表示,他将在那里存储“一堆城市”,所以,列表,惊喜! – quetzalcoatl
是的,@quetzalcoatl你应该是对的。这可能是一个进行中的工作。我发现代码中缺少的东西比描述中的要少。只是想填补空白。这是一个很好的意图! :) – AnjuRaj
@AnjuRaj为什么你需要在这种情况下的名单? 那么,因为到目前为止我已经学过了数组和列表,而且这个任务并没有让我使用任何我还没学过的东西。你会用什么?也许单变量,一个为Temp和一个为城市? – Gusto