Меню

Ошибка cs8802 только одна единица компиляции может содержать инструкции верхнего уровня

I just started learning c#, I created C# console application. To understand the concepts, I watched videos of how to setup vs code for c#

When I run the dotnet new console command in VS code terminal, it creates a new project including Program.cs file.

In the video, the Program.cs file appears like that

// Program.cs
using System;
namespace HelloWorld
{
  class Program
  {
    static string Main(string[] args)
    {
      Console.WriteLine("Hello, World!");
    }
  }
}

Program.cs in my IDE appears like,

// Program.cs
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

When I run the code using terminal dotnet run it runs perfectly on my computer.

when I create a new cs file, it contains

// hello.cs
Console.WriteLine("hello world");

after running it says Only one compilation unit can have top-level statements.

when I use class method and namespace like

// hello.cs
namespace helloworld
{
    class hello
    {
        static void Main()
        {
            Console.WriteLine("hello world");

        }
    }
}

it runs THE Program.cs file not the new file and shows this warning

PS C:UsersUserC#projects> dotnet run hello.cs C:UsersUserC#projectshello.cs(5,21): warning CS7022: The entry point of the program is global code; ignoring 'hello.Main()' entry point. [C:UsersUserC#projectsC#projects.csproj] Hello, World!

Project structure:

enter image description here

I tried another method by pressing run and debug and show nothing.

When I click on Generate c# Assets for Build and Debug button it shows this

Could not locate .NET Core project. Assets were not generated.

I just started learning c#, I created C# console application. To understand the concepts, I watched videos of how to setup vs code for c#

When I run the dotnet new console command in VS code terminal, it creates a new project including Program.cs file.

In the video, the Program.cs file appears like that

// Program.cs
using System;
namespace HelloWorld
{
  class Program
  {
    static string Main(string[] args)
    {
      Console.WriteLine("Hello, World!");
    }
  }
}

Program.cs in my IDE appears like,

// Program.cs
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

When I run the code using terminal dotnet run it runs perfectly on my computer.

when I create a new cs file, it contains

// hello.cs
Console.WriteLine("hello world");

after running it says Only one compilation unit can have top-level statements.

when I use class method and namespace like

// hello.cs
namespace helloworld
{
    class hello
    {
        static void Main()
        {
            Console.WriteLine("hello world");

        }
    }
}

it runs THE Program.cs file not the new file and shows this warning

PS C:UsersUserC#projects> dotnet run hello.cs C:UsersUserC#projectshello.cs(5,21): warning CS7022: The entry point of the program is global code; ignoring 'hello.Main()' entry point. [C:UsersUserC#projectsC#projects.csproj] Hello, World!

Project structure:

enter image description here

I tried another method by pressing run and debug and show nothing.

When I click on Generate c# Assets for Build and Debug button it shows this

Could not locate .NET Core project. Assets were not generated.

Comments

@munmunlina

Problem encountered on https://dotnet.microsoft.com/en-us/learn/dotnet/hello-world-tutorial/edit
Operating System: windows

Provide details about the problem you’re experiencing. Include your operating system version, exact error message, code sample, and anything else that is relevant.
// See https://aka.ms/new-console-template for more information
Console.WriteLine(«Hello, World!»);
Console.WriteLine(«The current time is » + DateTime.Now);

C:UsersMunmunlinaMyApp>dotnet run
C:UsersMunmunlinaMyAppProgram.cs(2,1): error CS8802: Only one compilation unit can have top-level statements. [C:UsersMunmunlinaMyAppMyApp.csproj]

The build failed. Fix the build errors and run again.

@jeffhandley

Hello @munmunlina. Thanks for submitting this issue.

That error leads me to believe you have another C# file in your MyApp folder, perhaps from a previous tutorial or step in the tutorial. If there are multiple C# files in the folder that have top-level statements (without being wrapped in classes/methods), then the compilation will fail with this message.

If Program.cs was the only C# file within this folder (or subfolders), then please reply here with the list of files and their contents that are in that folder.

2 participants

@jeffhandley

@munmunlina

В dotnet 6 для основного метода не требуется имя класса.

Поэтому, когда у вас есть 2 класса, у которых нет класса и пространства имен, компилятор думает, что у вас есть 2 основных метода.

Итак, вы делаете что-то вроде

namespace ConsoleApp1;

class Program1
{
    public static void GetRolling()
    {
        Random numberGen = new Random();

        int roll1 = 1;
        int roll2 = 0;
        int roll3 = 0;
        int roll4 = 0;

        int attempts = 0;

        Console.WriteLine("Press enter to roll the dies");

        while (roll1 != roll2 || roll2 != roll3 || roll3 != roll4 || roll4 != roll1)
        {
            Console.ReadKey();

            roll1 = numberGen.Next(1, 7);
            roll2 = numberGen.Next(1, 7);
            roll3 = numberGen.Next(1, 7);
            roll4 = numberGen.Next(1, 7);
            Console.WriteLine("Dice 1: " + roll1 + "nDice 2: " + roll2 + "nDice 3: " + roll3 + "nDice 4: " + roll4 + "n");
            attempts++;
        }

        Console.WriteLine("It took " + attempts + " attempts to roll a four of a kind.");
    }
}

А для программы2 некоторые думают так:

namespace ConsoleApp1;

public class Program2
{
    public static void Main(string[] args)
    {
        Program1.GetRolling();
        Console.ReadKey();
    }
}

В противном случае это все равно, что сказать 2 раза public static void Main(string[] args), а это невозможно.

Как исправить ошибку оператора верхнего уровня?

Программа1.cs Обычный файл C#, работает отлично.

Random numberGen = new Random();

int roll1 = 1;
int roll2 = 0;
int roll3 = 0;
int roll4 = 0;

int attempts = 0;

Console.WriteLine("Press enter to roll the dies");

while (roll1 != roll2 || roll2 != roll3 || roll3 != roll4 || roll4 != roll1)
{
    Console.ReadKey();

    roll1 = numberGen.Next(1, 7);
    roll2 = numberGen.Next(1, 7);
    roll3 = numberGen.Next(1, 7);
    roll4 = numberGen.Next(1, 7);
    Console.WriteLine("Dice 1: " + roll1 + "nDice 2: " + roll2 + "nDice 3: " + roll3 + "nDice 4: " + roll4 + "n");
    attempts++;
}

Console.WriteLine("It took " + attempts + " attempts to roll a four of a kind.");

Console.ReadKey();

Программа2.cs

Console.ReadKey();

Под модулем Консоль выскакивает ошибка:
Только одна единица компиляции может иметь операторы верхнего уровня. Ошибка: CS8802

Я пробовал в терминале новая консоль dotnet —force, но он просто удаляет мою программу.
Я хочу запустить несколько файлов C# в одной папке, не получая
Только одна единица компиляции может иметь операторы верхнего уровня. или другие подобные ошибки.


Canyon, 10 апреля 2022 г., 12:45

2

51

1


Ответ:

Решено

В dotnet 6 для основного метода не требуется имя класса.

Поэтому, когда у вас есть 2 класса, у которых нет класса и пространства имен, компилятор думает, что у вас есть 2 основных метода.

Итак, вы делаете что-то вроде

namespace ConsoleApp1;

class Program1
{
    public static void GetRolling()
    {
        Random numberGen = new Random();

        int roll1 = 1;
        int roll2 = 0;
        int roll3 = 0;
        int roll4 = 0;

        int attempts = 0;

        Console.WriteLine("Press enter to roll the dies");

        while (roll1 != roll2 || roll2 != roll3 || roll3 != roll4 || roll4 != roll1)
        {
            Console.ReadKey();

            roll1 = numberGen.Next(1, 7);
            roll2 = numberGen.Next(1, 7);
            roll3 = numberGen.Next(1, 7);
            roll4 = numberGen.Next(1, 7);
            Console.WriteLine("Dice 1: " + roll1 + "nDice 2: " + roll2 + "nDice 3: " + roll3 + "nDice 4: " + roll4 + "n");
            attempts++;
        }

        Console.WriteLine("It took " + attempts + " attempts to roll a four of a kind.");
    }
}

А для программы2 некоторые думают так:

namespace ConsoleApp1;

public class Program2
{
    public static void Main(string[] args)
    {
        Program1.GetRolling();
        Console.ReadKey();
    }
}

В противном случае это все равно, что сказать 2 раза public static void Main(string[] args), а это невозможно.


Maytham, 10 апреля 2022 г., 13:47

Интересные вопросы для изучения

Я только начал изучать С#, я создал консольное приложение С#. Чтобы понять концепции, я посмотрел видео о том, как настроить vs code для c#.

Когда я запускаю команду dotnet new console в терминале кода VS, он создает новый проект, включающий файл Program.cs.

В видео файл Program.cs выглядит так

// Program.cs
using System;
namespace HelloWorld
{
  class Program
  {
    static string Main(string[] args)
    {
      Console.WriteLine("Hello, World!");
    }
  }
}

Program.cs в моей среде IDE выглядит так:

// Program.cs
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

Когда я запускаю код с помощью терминала dotnet run, он отлично работает на моем компьютере.

Когда я создаю новый файл cs, он содержит

// hello.cs
Console.WriteLine("hello world");

После запуска он говорит Only one compilation unit can have top-level statements.

Когда я использую метод класса и пространство имен, например

// hello.cs
namespace helloworld
{
    class hello
    {
        static void Main()
        {
            Console.WriteLine("hello world");

        }
    }
}

Он запускает файл Program.cs, а не новый файл, и показывает это предупреждение

PS C:UsersUserC#projects> dotnet run hello.cs C:UsersUserC#projectshello.cs(5,21): warning CS7022: The entry point of the program is global code; ignoring 'hello.Main()' entry point. [C:UsersUserC#projectsC#projects.csproj] Hello, World!

Структура проекта:

enter image description here

Я попробовал другой метод, нажав run and debug и ничего не показав.

Когда я нажимаю кнопку Создать ресурсы c# для сборки и отладки, отображается это

Не удалось найти проект .NET Core. Активы не генерировались.

1 ответ

Лучший ответ

Функция C# 9: операторы верхнего уровня

Это новая функция C# 9, которая называется Утверждения верхнего уровня

Видео, на которое вы ссылаетесь, может использовать более низкую версию C# (ниже, чем C# 9). Где мы используем, чтобы получить

namespace helloworld
{
    class hello
    {
        static void Main()
        {
            Console.WriteLine("hello world");  
        }
    }
}

Как стандартная структура основной программы.

Если вы внимательно посмотрите, вы обнаружите только одну строку кода, которая выводит строку на консоль, т.е.

Console.WriteLine("hello world");  

Операторы верхнего уровня были введены для удаления ненужных церемоний из этого консольного приложения.

Поскольку вы используете C#9 или выше, dot net run с оператором верхнего уровня успешно компилирует ваш код, но когда вы заменяете однострочный код на устаревшую структуру, компилятор предупреждает вас о глобальной записи функции Main и Функция Main(), которую вы добавили, заменив оператор верхнего уровня.

Чтобы получить больше ясности, вы можете просмотреть документацию MSDN: Утверждения верхнего уровня


Почему вы получаете сообщение об ошибке «Только одна единица компиляции может иметь операторы верхнего уровня»?

  • Согласно документация MSDN. Приложение должно иметь только одну точку входа.
  • В проекте может быть только один файл с операторами верхнего уровня.
  • Когда вы создали новый файл, вы добавили новый оператор верхнего уровня, что привело к следующей ошибке времени компиляции:

CS8802 Только одна единица компиляции может иметь операторы верхнего уровня.


как это исправить?

  • Согласно приведенному выше объяснению, ваш проект не должен содержать двух или более операторов верхнего уровня. Чтобы исправить эту ошибку, вы можете удалить файл, который был добавлен позже.


6

Prasad Telkikar
7 Июн 2022 в 18:39

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка createprocess сбой код 2 не удается найти указанный файл
  • Ошибка createprocess returned 2