1 值傳遞
函數定義時可以設默認值,調用函數時不傳參數則函數內部使用默認值,設置默認值的參數必須放在末尾
值傳遞還有可變參數的傳遞 關鍵字 params
2 引用傳遞 ref關鍵字
函數定義時不能設默認值
3 輸出傳遞 out關鍵字
函數定義時不能設默認值
注意:使用out關鍵字傳遞的參數需要在函數內部初始化
/// <summary>
/// C#參數傳遞方式
/// </summary>
class Program
{
static void Main(string[] args)
{
int a = 0;
TestValue(a);
Console.WriteLine("**值傳遞*輸出 a={0}", a);
a = 0;
TestRef(ref a);
Console.WriteLine("引用傳遞*輸出 a={0}", a);
a = 0;
TestOut(out a);
Console.WriteLine("輸出傳遞*輸出 a={0}", a);
//可變參數的兩種傳參方式
TestParams(a, 1, 2, 3, 1);
int[] b = new int[] { 5,6,8,9};
TestParams(b);
}
/// <summary>
/// 1值傳遞
/// </summary>
static void TestValue(int a,int b=6)
{
Console.WriteLine("**值傳遞*輸入 a={0}", a);
a = 10+b;
}
/// <summary>
/// 引用傳遞
/// </summary>
static void TestRef(ref int a)
{
Console.WriteLine("引用傳遞*輸入 a={0}", a);
a = 10;
}
/// <summary>
/// 輸出傳遞
/// </summary>
static void TestOut(out int a)
{
//參數處於未賦值的狀態,必須在函數內部初始化
//Console.WriteLine("輸出傳遞*輸入 a={0}", a);
a = 10;
}
/// <summary>
/// 可變參數
/// </summary>
/// <param name="a">可以傳遞一個數組,也可以傳遞單獨的數組元素</param>
static void TestParams(params int[] a)
{
foreach (var item in a)
{
Console.Write(item + " ");
}
Console.WriteLine();
}
}
以上代碼輸出結果:

