C# 参数传递 引用类型与值类型的值传递和引用传递

时间:2022-08-29 20:23:09
///变长参数的例子
class Program
{
static void Main(string[] args)
{
ShowAgeSum(
"w", 1, 2, 3, 4);
ShowAgeSum(
"h", 1, 1, 1);
ShowAgeSum(
"c", 99, 1, 2, 3, 4, 1, 0, 0, 0, 0, 0, 0, 100000);
Console.Read();
}

static void ShowAgeSum(string team, params int[] ages)
{
int ageSum = 0;
for (int i = 0; i < ages.Length; i++)
ageSum
+= ages[i];
Console.Write(
"{0}'s age is {1}\r\n",team,ageSum);
}
}
///值类型参数 按值传递 和按引用传递的区别
class Program
{
static void Main(string[] args)
{
int a = 0;
Add(a);
Console.WriteLine(a);
Add(
ref a);
Console.WriteLine(a);
Console.Read();
}

static void Add(int i)
{
i
= i + 10;
Console.WriteLine(i);
}

static void Add(ref int i)
{
i
= i + 10;
Console.WriteLine(i);
}
}
结果:
10,0,10,10

///引用类型参数 按值传递和按引用传递的区别
class Program
{
static void Main(string[] args)
{
ArgsByRef a
= new ArgsByRef();
Add(a);
Console.WriteLine(a.i);
Add(
ref a);
Console.WriteLine(a.i);
Console.Read();
}

static void Add(ArgsByRef a)
{
a.i
= 20;
Console.WriteLine(a.i);
}

static void Add(ref ArgsByRef a)
{
a.i
= 30;
Console.WriteLine(a.i);
}


}
class ArgsByRef
{
public int i = 10;
}
结果 :
20,20,30,30

///字符串参数的按值与按引用传递 与 值类型一致 (string 是引用类型)
class Program
{
static void Main(string[] args)
{
string a = "Old String";
Add(a);
Console.WriteLine(a);
Add(
ref a);
Console.WriteLine(a);
Console.Read();
}

static void Add(string a)
{
a
= "new String";
Console.WriteLine(a);
}

static void Add(ref string a)
{
a
= "new String";
Console.WriteLine(a);
}
}
结果:
new String, Old String,new String,new String;