您的位置:首页 > 编程语言 > C#

C# 程序入口(Main)

2006-03-18 00:47 316 查看
一、C#程序入口(Main)
static void Main()
{
}
static int Main()
{
}
static void Main(string[] args)
{
}
static int Main(string[] args)
{
}
1.主程序Main函数一共有以上四种版
2.一个程序中不能有两个以上的Main函数,有且只有一个
3.Main函数只能返回int类型,如果返回1,则从命令行调用不成功。否则成功
4.在命令行传输参数时,存放在string数组args中。使用Length属性来测试输入参数的个数。
5.使用foreach语句来检索所有的参数
5.程序入口主要供其他程序来执行本程序功能

二、例程
//Main() 和命令行参数

/*以检举数组中所有元素访问信息
for each (string str int args(
Console.WriteLine(str);*/
using System;
using System.Collections.Generic;
using System.Text;

namespace HelloWorld
{
class Program
{
public static long getx(int x) //阶乘 (注:使用Static定义的方法不用实例化就能使用)
{
long y = 1;
for (int i = 2; i<=x; i++)
{
y =y * i;
}
return y;
}
public static long gety(int x) //阶加
{
long y = 0;
for (int i = 1; i <= x; i++)
{
y += i;
}
return y;
}
static int Main(string[] args)
{
if (args.Length != 1) //测试args[]数组的长度 ------即是输入的命令行的参数是多少
{
Console.WriteLine("程序使用说明:输入一个整数来算出其的阶乘.");
Console.WriteLine(" 输入一个整数来算出其的阶加.");
}
else if (Convert.ToInt32(args[0]) < 1 )
{
Console.WriteLine("输入参数不能小于1");
}
else
{
int x; long y,z;
try
{
x = Convert.ToInt32(args[0]);
y = getx(x);
z = gety(x);
Console.WriteLine(x + "的阶乘为: " + y);
Console.WriteLine(x + "的阶加为: " + z);
return 1; //返回1表示调用程序成功执行
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
}

三、执行结果



作者: GX
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: