You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#程序报错:公共类需含Public Main()方法及GitHub Actions类名问题

问题解决:C#入口类与Main方法访问修饰符问题

错误原因

两个平台的报错本质都是入口类和Main方法的访问修饰符不符合平台要求:

  • DotNetFiddle明确要求程序入口必须是public类中的public static Main方法
  • GitHub Actions的编译环境在识别程序入口时,需要入口类为public才能正确定位

修改后的代码

using System;

public class HelloWorld
{
    public static int GetYear()
    {
        Console.WriteLine("Please enter year: ");
        int year = Convert.ToInt32(Console.ReadLine());
        return year;
    }

    public static int GetMonth()
    {
        Console.WriteLine("Please enter month number (February is 2): ");
        int month = Convert.ToInt32(Console.ReadLine());
        return month;
    }

    static string GetMonthName(int month)
    {
        string[] monthName = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
        string monthValue = monthName[month - 1];
        return monthValue;
    }

    public static bool LeapYear(int Year)
    {
        return ((Year % 4 == 0 && Year % 100 != 0) || Year % 400 == 0);
    }

    public static void Print(string monthValue, int days, int year, int month)
    {
        Console.WriteLine("{0} {1} has {2} days", year, monthValue, days);
    }

    public static void Main()
    {
        int[] days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        int[] leapDays = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        int monthDays;

        while (true)
        {
            int year = GetYear();
            int month = GetMonth();
            if (year > 0 && month > 0 && month <= 12)
            {
                string monthValue = GetMonthName(month);
                bool leap = LeapYear(year);

                monthDays = leap ? leapDays[month - 1] : days[month - 1];
                Print(monthValue, monthDays, year, month);
            }
            else
            {
                Console.WriteLine("Invalid Year or Month entered!! Please enter a correct value");
                break;
            }
        }
    }
}

关键修改点

  • 将class HelloWorld改为public class HelloWorld:让入口类对编译环境可见
  • 将static void Main()改为public static void Main():满足DotNetFiddle对入口方法的访问修饰符要求
  • 顺带修正了细节问题:
    1. Febuary拼写错误改为February
    2. print方法名改为Print,符合C# PascalCase命名规范
    3. 简化LeapYear方法的返回逻辑,让代码更简洁

验证说明

修改后代码可在DotNetFiddle正常运行,同时满足GitHub Actions的编译要求,彻底解决两个平台的报错问题。

内容的提问来源于stack exchange,提问作者FervidActor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 09:01:45