日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Top-level statements must precede namespace and type declarations. [Test]csharp(CS8803)

作者:Morris_ 更新時間: 2022-04-12 編程語言

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 的定義以及它的構造函數。

我猜,這個問題在其他的應用程序中應該不會存在,只是出現在控制臺應用程序這種從上往下有嚴格執行順序的應用程序中。

在這里插入圖片描述

  • C# 結構體
  • 結構體類型數組

代碼如下:

// 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);
    }
}

原文鏈接:https://blog.csdn.net/Morris_/article/details/123471477

欄目分類
最近更新