码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-10-08 20:08:15      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/mamiyiya777/p/5939472.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!