初学者C#.NET错误:如果args没有长度,为什么我的书会这样写呢?

0 c# visual-studio-2005

我最近开始学习C#.NET,并一直使用Visual Studios 2005作为我的IDE.我直接从教科书中复制了这段代码,它给了我下面的错误.我想要接收的输出是:请输入一个数字参数:1但是我收到此错误:由于ConsoleApplication1.Program.Main(string [])'返回void,因此返回关键字后面的对象表达式不能出现

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            if(args.Length == 0)
            {
                Console.WriteLine("Please enter a numeric argument: ");
                return 1;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Bel*_*gix 5

这是因为你Main标记为void.这意味着它只会让你打电话return.如果要返回退出代码(如示例所示),则需要更改Main方法以返回int:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        // Make this int instead of void
        static int Main(string[] args)
        {
            if(args.Length == 0)
            {
                Console.WriteLine("Please enter a numeric argument: ");
                return 1;
            }

            // Default return value
            return 0;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)