C#
.NET 6
结构体
C# 控制台应用程序定义了一个结构体,然后创建结构体实例,报如下错误:
Top-level statements must precede namespace and type declarations. [Test]csharp(CS8803)
把 Student stu1 = new Student(“小明”,22); 结构体的定义放在初始化的后面就不报错了,这是为什么?
我个人的理解是因为C#控制台应用程序,从上往下执行,执行到 Student stu1 = new Student(“小明”,22); 然后再去找 Student 的定义以及它的构造函数。
我猜,这个问题在其他的应用程序中应该不会存在,只是出现在控制台应用程序这种从上往下有严格执行顺序的应用程序中。
代码如下:
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");
Student stu1 = new Student("小明",22);
Student stu2 = new Student("小红",23);
Student stu3 = new Student("小丽",20);
Student stu4 = new Student("小王",21);
Student [] array = new Student[4]; // 初始化数组 类型 [] 数组名 = new 类型[容量]
array[0] = stu1;
array[1] = stu2;
array[2] = stu3;
array[3] = stu4;
foreach (Student stu in array) { // 遍历数组 foreach(类型 变量名 in 数组名)
Console.WriteLine("{0}的年龄是{1}",stu.name, stu.age); // 打印输出姓名和年龄
}
public struct Student { // 定义结构体Student
public string name;
public int age;
public Student(string name, int age) { // 构造函数
this.name = name;
this.age = age;
}
public void PrintStudent() {
Console.WriteLine(this.name,this.age);
}
}