随便玩玩之C# 18 数据类型:类和对象初始化
随便玩玩之C# 18 数据类型:类和对象初始化
接上一节,存张三的成绩就初始化一个张三的对象,那存李四的成绩呢,就初始化一个李四的对象,王五呢,赵六呢。数据一多,代码看着就难受。那么多重复的代码。
有没有一种简单的方法,存放张三李四王五赵六的成绩,而不需要那么多重复的冗余代码?
答案是有。使用对象初始化器即可和集合即可解决。
还记得在对象的实例化时的语句吗?
Student StudentResult = new Student();
最后一对括号,上一节说了是可以调用构造函数。
这里,我们把它变成大括号{},他就是 一个对象初始化器。
Student Students = new Student { };
在打括号内就可以给对象赋值。
Student Students = new Student { Id = 3,Name="张三"};
完整的代码
using System;
namespace ObjectAndCollectionInitializers
{
internal class Program
{
static void Main(string[] args)
{
Student Students = new Student { Id = 3,Name="张三"};
Console.WriteLine(Students.Id);
Console.WriteLine(Students.Name);
Console.WriteLine(Students.Chinese);
Console.WriteLine(Students.Math);
Console.ReadKey();
}
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Chinese { get; set; }
public int English { get; set; }
public int Math { get; set; }
}
}
那么,处理多个学生的成绩呢?
那就创建一个类的类型的数组。
using System;
namespace ObjectAndCollectionInitializers
{
internal class Program
{
static void Main(string[] args)
{
Student[] Students = new Student[] {
new Student{Id = 3,Name="张三"},
new Student{Id = 4,Name="李四"},
new Student{Id = 5,Name="王五"}
};
//这里没有输出语句。调试不会显示内容。
Console.ReadKey();
}
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Chinese { get; set; }
public int English { get; set; }
public int Math { get; set; }
}
}
第9行多了两对中括号(方括号),表示创建了包含Student类模板的Students的数据集合。
使用大括号表示数据集合的数据,里面的每一行(10-12行)都是一个实例化的对象,只不过没有对象名称。每一个对象用逗号隔开。
这时,如果要输出这个对象集合的值,就需要用到Foreach循环,因为里面的每一个都是对象。
using System;
namespace ObjectAndCollectionInitializers
{
internal class Program
{
static void Main(string[] args)
{
Student[] Students = new Student[] {
new Student{Id = 3,Name="张三"},
new Student{Id = 4,Name="李四"},
new Student{Id = 5,Name="王五"}
};
foreach (Student student in Students)
{
Console.WriteLine(student.Name);
Console.WriteLine(student.Id);
Console.WriteLine(student.English);
}
Console.ReadKey();
}
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Chinese { get; set; }
public int English { get; set; }
public int Math { get; set; }
}
}
参考:
https://learn.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers

浙公网安备 33010602011771号