每個 C# 應用程式必須且只能有一個 Main() 方法,作為程式執行起點。注意 C# 採用大寫 Main,而 Java 使用小寫 main。
Main() 只能回傳 int 或 void,並可選擇性接收字串陣列參數代表命令列引數:
static int Main(string[] args)
{
...
return 0;
}
字串陣列 args 包含命令列參數,args[0] 為第一個參數,以此類推。與 C++ 不同,args 不包含 EXE 檔名稱。
在 Java 與 C# 中,參考型別參數預設以參考傳遞,實值型別則以值傳遞。但 C# 所有參數預設皆為值傳遞,欲以參考傳遞必須明確指定 ref 或 out:
ref:參數必須先初始化out:無需預先初始化,舊值會被忽略當方法參數為參考型別時,參考本身以值傳遞,但仍指向同一物件,因此修改物件屬性會保留;若在方法內將參考指向新物件,方法結束後原參考不變。
using System;
public class RefClass
{
public static void Main(string[] args)
{
int total = 20;
Console.WriteLine("Original value of 'total': {0}", total);
Add(10, ref total);
Console.WriteLine("Value after Add() call: {0}", total);
}
public static void Add(int i, ref int result)
{
result += i;
}
}
輸出:
Original value of 'total': 20
Value after Add() call: 30
result 參考了呼叫端 total 的實際記憶體位址。注意:類別屬性不能直接作為 ref 參數。呼叫與宣告時皆須加上 ref 關鍵字。