问题描述
对于大多数人(熟练的程序员)来说,标题听起来似乎不太好,但是我正在学习C#基础知识的第三周,我无法弄清楚如何解决下一个任务。
我将为一堆城市存储一些温度,首先要求用户输入cityName,然后再询问该城市的实际温度。所有这些东西都应该保存在列表中,并且我将使用Class和Constructor。
当我尝试打印结果(使用foreach)时,它打印出我的名称空间的名称和类的名称,例如 Task_5.City。
我的代码有什么问题:
Probably the title doesn't sound very well for most of you guys (skilled programmers), but I'm on my 3rd week of learning C# fundamentals and I cant figure it out how to solve the next task.I shall store some temperatures for a bunch of cities, asking a user for a cityName first and then for the actual temp in that city. All this stuff should be saved in a list<> and I shall use Class and Constructor.When I try to print out the result (using foreach) it prints out the name of my namespace and the name of my class like "Task_5.City"Whats wrong with my code:
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();
}
}
推荐答案
您正在将对象传递给 Console.WriteLine(item)
,而不是传递字符串。 Console.WriteLine
调用该对象的 ToString()
方法,默认情况下返回名称空间+类名。您可以像下面这样覆盖此行为:
You are passing object to the Console.WriteLine(item)
instead of passing the string. Console.WriteLine
invokes ToString()
method of that object that by default returns namespace+class name. You can override this behavior like next:
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;
}
public override string ToString()
{
return string.Format("{0} {1}", CityName, Temperature);
}
}
或者您可以使用另一个重载 WriteLine
方法:
Or you can use another overload of WriteLine
method:
Console.WriteLine("{0} {1}", item.CityName, item.Temperature);
这篇关于为什么将项目写入控制台仅写入名称空间和类名称,而不写入数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!