Main方法有一个参数是string[],有一个返回值是int,作用是什么呢?
参数,是一个方法调用别一个方法时传入的变量,Main方法又是一个程序的入口方法,这上参数一定是别的程序调用时传进来的,看这样一个程序:
被调程序代码:
1
using System;
2
using System.Collections.Generic;
3
using System.Text;
4
class Mains
5
{
6
static void Main(string[] args)
7
{
8
if (args.Length > 0)
9
{
10
Console.WriteLine(args[0]);
11
Console.ReadLine();
12
}
13
}
14
}
15
调用程序:
2

3

4

5



6

7



8

9



10

11

12

13

14

15

1
using System;
2
using System.Collections.Generic;
3
using System.Text;
4
using System.Diagnostics;
5
6
class Mains
7
{
8
static void Main(string[] args)
9
{
10
Process.Start(@"F:\b.exe", "这是参数");
11
}
12
}
13

2

3

4

5

6

7



8

9



10

11

12

13

注意,被调用的程序,编译好后命名成b.exe放在F盘下,这样才能正确调用。
这个参数能很好的在两个程序集之间传输信息,这样对项目的分割提供了可能。
另一方面,可以看一下Main方法的返回值,返回值的类型是int,这个值又给了谁了呢?有的朋友说返回了调用本程的方法,但这个说法不正确,这个返回值返回给一个名称为ERRORLEVEL的环境变量,我们可以用批处理命令来查看这个变量,如下面代码:
先定义一个Main方法:
1
using System;
2
using System.Collections.Generic;
3
using System.Text;
4
using System.Diagnostics;
5
class Mains
6
{
7
static int Main(string[] args)
8
{
9
Console.WriteLine("返回值为114");
10
return 114;
11
}
12
}
13
批处理命令为:
2

3

4

5

6



7

8



9

10

11

12

13

@echo %ERRORLEVEL%
把这个命令用txt文档保存,并把扩展名改成bat
打开“Visual Studio 2005 命令提示”,先运行主程序,后运行批处理命令,你会发现批处理的结果就是Main方法的返回值。