首页 > 代码库 > 引用参数,值参数,ref,out

引用参数,值参数,ref,out

1,一个参数只有在引用的时候才能改变其值,这是一种情况

2,一个参数在引用后要永久的改变其值(可以用返回参数的形式)

3,多个参数在引用后要永久的改变其值或者多个参数中的部分(返回参数就适合了,因为只能返回一个,所以就用REF和4.OUT了)

上例子

1

技术分享
static void ShowDouble(int val){val *= 2;Console.WriteLine("val doubled = {0}", val);}int myNumber = 5;Console.WriteLine("myNumber = {0}", myNumber);ShowDouble(myNumber);Console.WriteLine("myNumber = {0}", myNumber);
View Code

2

技术分享
static int DoubleNum(int val){val *= 2;return val;}int myNumber = 5;Console.WriteLine("myNumber = {0}", myNumber);myNumber = DoubleNum(myNumber);Console.WriteLine("myNumber = {0}", myNumber);
View Code

3。REF

技术分享
static void ShowDouble(ref int val){val *= 2;Console.WriteLine("val doubled = {0}", val);}int myNumber = 5;Console.WriteLine("myNumber = {0}", myNumber);ShowDouble(ref myNumber);Console.WriteLine("myNumber = {0}", myNumber);
View Code


4. OUT

技术分享
static int MaxValue(int[] intArray, out int maxIndex){int maxVal = intArray[0];maxIndex = 0;for (int i = 1; i < intArray.Length; i++){if (intArray[i] > maxVal){maxVal = intArray[i];maxIndex = i;}}return maxVal;}int[] myArray = { 1, 8, 3, 6, 2, 5, 9, 3, 0, 2 };int maxIndex;Console.WriteLine("The maximum value in myArray is {0}",MaxValue(myArray, out maxIndex));Console.WriteLine("The first occurrence of this value is at element {0}",maxIndex + 1);
View Code

 

引用参数,值参数,ref,out