加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 为什么写项目到控制台只写命名空间和类名而不是数据?

发布时间:2020-12-15 19:28:25 所属栏目:百科 来源:网络整理
导读:参见英文答案 WriteLine with a class????????????????????????????????????9个 对于大多数人(熟练的程序员)来说,标题听起来不太好,但我正在学习C#基础知识的第3周,我无法弄清楚如何解决下一个任务. 我将为一堆城市存储一些温度,首先向用户询问cityName,然后
参见英文答案 > WriteLine with a class????????????????????????????????????9个
对于大多数人(熟练的程序员)来说,标题听起来不太好,但我正在学习C#基础知识的第3周,我无法弄清楚如何解决下一个任务.
我将为一堆城市存储一些温度,首先向用户询问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();

    }
}

解决方法

您正在将对象传递给Console.WriteLine(item)而不是传递字符串. Console.WriteLine调用该对象的ToString()方法,该方法默认返回命名空间类名.您可以像下一样覆盖此行为:

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方法的另一个重载:

Console.WriteLine("{0} {1}",item.CityName,item.Temperature);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读