一、params. 可變參數,無論有幾個參數,必須出現在參數列表的最後,可以為可變參數直接傳遞一個對應類型的數組。 二、ref 引用傳遞 三、out out 參數在使用之前必須在方法里為out參數賦值。 out參數無法獲取實參傳來的值。所以在主函數 中,只需聲明函數就行。它也是引用。 out一般用在 ...
一、params.
可變參數,無論有幾個參數,必須出現在參數列表的最後,可以為可變參數直接傳遞一個對應類型的數組。
class Program { static void Main(string[] args) { Test("msg"); Test("msg", 1, 2, 3); int[] intArry = new int[] { 1, 2, 3 }; Test("msg", intArry); } static void Test(string msg,params int[] args) { } }
二、ref
引用傳遞
三、out
out 參數在使用之前必須在方法里為out參數賦值。
out參數無法獲取實參傳來的值。所以在主函數 中,只需聲明函數就行。它也是引用。
out一般用在函數有多個返回值。
參數前加ref out 不能算重載。
class Program
{
static void Main(string[] args)
{
Test(out int x);
Console.WriteLine(x);
}
static void Test(out int x)
{
x = 100;
}
}
out 實例:
class Program { static void Main(string[] args) { Console.WriteLine("輸入用戶名"); string id = Console.ReadLine(); Console.WriteLine("輸入密碼"); string psw = Console.ReadLine(); bool isok=Login(id, psw, out string msg); if (isok) { Console.WriteLine(msg); } else { Console.WriteLine(msg); } } private static bool Login(string id, string psw, out string msg) { bool isok = false; if (id!="admin") { msg = "用戶名錯誤"; } if (psw!="123") { msg = "密碼錯誤"; } else { isok = true; msg = "登錄成功"; } return isok ; } }