C#中对象的输出

时间:2021-08-14 05:21:10

假设有个Costmer类如下:

    class Costmer
{
public string Id { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Region { get; set; }
public string Sales { get; set; } public Costmer(string id,string city,string country,string region,string sales)//构造函数
{
Id = id;
City = city;
Country = country;
Region = region;
Sales = sales;
}
public override string ToString()//重写ToString()方法,以便于输出
{
return "ID:" + Id + " City:" + City + " Country:" + Country + " Region:" + Region + " Sales:" + Sales;
}
}

创建两个 Costmer 类的实例,然后分别输出:

        Costmer c = new Costmer("", "乐山", "中国", "四川", "");
Costmer d = new Costmer("", "成都", "中国", "四川", "");
Console.WriteLine(c);
Console.WriteLine(d);

结果如下:

C#中对象的输出

我们也可以不完全输出类的值,只输出一部分信息,比如我们这里只输出:ID,City,Country的值:

则代码如下:

            Costmer c = new Costmer("", "乐山", "中国", "四川", "");
Costmer d = new Costmer("", "成都", "中国", "四川", "");
Console.WriteLine("ID:{0} City={1} Country={2}",c.Id,c.City,c.Country);
Console.WriteLine("ID:{0} City={1} Country={2}", d.Id, d.City, d.Country);

结果:

C#中对象的输出

注意:假若 Costmer 类中没有对 ToString()方法进行重写,则输出结果为:

C#中对象的输出

但是当有多个对象的时候,我们需要将这些对象放在集合中,然后再输出,为此,我们需要创建一个泛型集合

创建一个Costmer类的泛型集合,并向集合中添加 对象

        List<Costmer> costmers = new List<Costmer>();
costmers.Add(new Costmer("","乐山","中国","四川",""));
costmers.Add(new Costmer("","成都","中国","四川",""));
costmers.Add(new Costmer("", "重庆", "中国", "重庆", ""));

输出对象的值:

        for (int i = ; i < costmers.Count; i++)
{
Console.WriteLine(costmers[i]);
}

结果:

C#中对象的输出

同理也可以只输出对象一部分的值:  在"."后加入对象需要输出的属性值即可

        for (int i = ; i < costmers.Count; i++)
{
Console.WriteLine(costmers[i].City);
}

使用Linq输出对象:

       var queryResults = from n in costmers where n.Region == "四川" select n;  //注意 是两个=号,这是不是赋值,是判断

            foreach (var item in queryResults)
{
Console.WriteLine(item.ToString());
}

结果:

C#中对象的输出