Main方法是C#控制台应用程序和Windows窗体应用程序的入口点。Main方法可以有形参,也可以没有,可以有返回值(int整型),也可以没有。如下定义:

无返回值、无形参的格式:
static void Main(){
    //to do sth  
}

无返回值、有形参的格式:
static void Main(string[] args){
    //to do sth  
}

有返回值、无形参的格式:
static int Main(){
    //to do sth  
    return 0;
}

有返回值、有形参的格式:
static int Main(string[] args){
    //to do sth  
    return 0;  
}

Main方法必须为静态形式,访问修饰符不能为public。因C#类中默认的访问修饰符为private,因此可以不写。

在外部可以通过输入命令行参数的形式启动应用程序,从而进入程序的入口(Main方法)。

在开始菜单中打开“Visual Studio开发人员命令提示”窗口,然后导航到cs文件所在目录。用csc命令编译包含Main方法的cs文件,如:csc test.cs。如果编译成功,当下目录会生成一个test.exe应用程序,这时可用test param1 param2命令调用应用程序并执行应用程序,每个参数之间用空格隔开,如果参数中有空格,就用双引号将该参数围着,这样应用程序就会将它识别为一个参数,而不是多个。

命令行输入格式如下:

命令行输入格式 传递给Main方法的字符串数组格式
test one two three

"one"

"two"

"three"

test a b c

"a"

"b"

"c"

test "one two" three

"one two"

"three"

 

 

 

 

 

 

 

 

 

 

 

测试代码如下:

class test{
    static int Main(string[] args){
        int count=1;
        if(args!=null && args.Length>0)
            foreach(string item in args)
                System.Console.WriteLine("第{0}个参数:{1}",count++,item);
        else
            System.Console.WriteLine("没有输入任何参数!");
        System.Console.WriteLine("程序结束!");
        return 0;
    }
}

测试结果如图:

 

可以用批处理文件来运行C#应用程序,并根据应用程序返回的整型结果进行下一步逻辑操作。

在Windows中执行程序时,Main方法返回的任何值都将保存到名为ERRORLEVEL的环境变量中。可以通过检查ERRORLEVEL变量的值,批处理文件可以确定程序执行的结果。通常可以将返回值设置为0,用来表示程序执行成功的标志。

 test.bat批处理文件内容如下:

rem test.bat
@echo off
test one two three
@if "%ERRORLEVEL%" == "0" goto Success

:Failed
	echo program execute failed
	echo the return value is %ERRORLEVEL%
	goto End

:Success
	echo program execute success
	echo the return value is %ERRORLEVEL%
	goto End
	
:End
	
pause

批处理test.bat执行结果如下:

 

 posted on 2016-11-29 17:28  F风  阅读(4781)  评论(0编辑  收藏  举报