首页 > 解决方案 > “顶级语句必须在命名空间和类型声明之前”

问题描述

所以我没有长时间编码所以我没有那么有经验,我最近在 replit.com 上遇到了一个问题,控制台会打印出来:

error CS8803: Top-level statements must precede namespace and type declarations.
using System;

任何人都可以提出这个问题吗?这是我的代码给任何想知道的人:

int English;
int Science;
int AverageCalc;

AverageCalc = Convert.ToInt32(Console.ReadLine());

class Program {
  public static void Main (string[] args) {
    Console.WriteLine("Write your math grades");

      Math = Convert.ToInt32(Console.ReadLine());

      Console.WriteLine("Write your english grades");

      English = Convert.ToInt32(Console.ReadLine());

      Console.WriteLine("Write your science grades");

      Science = Convert.ToInt32(Console.ReadLine());

      AverageCalc = (Math+English+Science/3);
  }
}

if (AverageCalc > 80)
{
  Console.WriteLine("You passed with A mark!");
}
else if (AverageCalc < 80)
{
  Console.WriteLine("You passed with B mark!");
}
else if (AverageCalc < 65)
{
  Console.WriteLine("You passed with C mark!");
}
else if (AverageCalc < 60)
{
  Console.WriteLine("You passed with D mark!");
}
else if (AverageCalc < 55)
{
  Console.WriteLine("You got lower than D mark, try better next time.");
}

标签: c#

解决方案


正如@Caius 在他的回答中提到的,您正在修复代码中的顶级语句和经典方式。

您可以按照他建议的方法,或者只是从您的代码中删除以下部分。

class Program
{
    public static void Main (string[] args) 
    {

并关闭}ProgramMain方法。

示例取自文档

下面的代码是一样的。

using System;

namespace Application
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

TLS

Console.WriteLine("Hello, World!");

推荐阅读