C# Main函數(shù)概念以及應(yīng)用祥解
C# Main函數(shù)的概念是什么呢?C# Main()是C#應(yīng)用程序的入口點,執(zhí)行這個函數(shù)就是執(zhí)行應(yīng)用程序。也就是說,在執(zhí)行過程開始時,會執(zhí)行Main()函數(shù),在Main()函數(shù)執(zhí)行完畢時,執(zhí)行過程就結(jié)束了。
C# Main函數(shù)的四種情況:
- static void Main()
- {
- }
- static int Main()
- {
- }
- static void Main(string[] args)
- {
- }
- static int Main(string[] args)
- {
- }
1.主程序Main函數(shù)一共有以上四種版
2.一個程序中不能有兩個以上的Main函數(shù),有且只有一個
3.Main函數(shù)只能返回int類型,如果返回1,則從命令行調(diào)用不成功。否則成功
4.在命令行傳輸參數(shù)時,存放在string數(shù)組args中。使用Length屬性來測試輸入?yún)?shù)的個數(shù)。
5.使用foreach語句來檢索所有的參數(shù)
6.程序入口主要供其他程序來執(zhí)行本程序功能
C# Main函數(shù)實例:
- //Main() 和命令行參數(shù)
- /*以檢舉數(shù)組中所有元素訪問信息
- 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[]數(shù)組的長度 ------即是輸入的命令行的參數(shù)是多少
- {
- Console.WriteLine("程序使用說明:輸入一個整數(shù)來算出其的階乘.");
- Console.WriteLine(" 輸入一個整數(shù)來算出其的階加.");
- }
- else if (Convert.ToInt32(args[0]) < 1 )
- {
- Console.WriteLine("輸入?yún)?shù)不能小于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表示調(diào)用程序成功執(zhí)行
- }
- catch(Exception ex)
- {
- Console.WriteLine(ex.ToString());
- }
- }
- }
- }
- }
C# Main函數(shù)實例執(zhí)行結(jié)果
C# Main函數(shù)的概念和實例的基本內(nèi)容就向你介紹到這里,希望對你了解和學(xué)習(xí)C# Main函數(shù)有所幫助。
【編輯推薦】