核心規則
方法內部必須初始化:在方法體中,必須在方法返回前對?
out
?參數顯式賦值(未賦值會導致編譯錯誤)調用時無需初始化:調用方傳遞?
out
?參數前不需要初始化變量(可直接使用未賦值的局部變量)
下面是示例代碼?
static void Main(string[] args)
{Console.WriteLine("請輸入用戶名");string thisname = Console.ReadLine();Console.WriteLine("請輸入密碼");string thispwd=Console.ReadLine();string thismsg;bool thisresult= userpwd(thisname, thispwd, out thismsg);Console.WriteLine("{0}", thismsg);Console.WriteLine("登錄狀態為{0}", thisresult);Console.ReadKey();
}//out 參數需要在函數體內部初始化,然后引用的時候無需初始化
public static bool userpwd(string username,string pwd,out string msg)
{if (username=="admin" && pwd=="0000"){msg = "登錄成功";return true;}else if (username == "admin"){msg = "登錄失敗";return false;}else if (pwd == "admin"){msg = "登錄失敗";return false;}else{msg = "未知錯誤";return false;}}
與ref的對比