C# Main函數概念以及應用祥解
C# Main函數的概念是什么呢?C# Main()是C#應用程序的入口點,執行這個函數就是執行應用程序。也就是說,在執行過程開始時,會執行Main()函數,在Main()函數執行完畢時,執行過程就結束了。
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語句來檢索所有的參數
6.程序入口主要供其他程序來執行本程序功能
C# Main函數實例:
- //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());
- }
- }
- }
- }
- }
C# Main函數實例執行結果
C# Main函數的概念和實例的基本內容就向你介紹到這里,希望對你了解和學習C# Main函數有所幫助。
【編輯推薦】