C#:ref(引用传递参数)和out(输出参数))

来源:互联网 发布:php图片上传 编辑:程序博客网 时间:2024/06/05 05:33

ref:

class refFunc{    static void ShowNum(ref int num)    {        num *= 2;        WriteLine($"num int = {num}");    }    static void Main(string[] args)    {        int mNum = 5;        WriteLine($"mNum = {mNum}");  //5        ShowNum(ref mNum);            //10        WriteLine($"mNum = {mNum}");  //10    }}

用做ref参数的变量有两个限制:
1.必须在函数调用时,使用变量(不能使用常量);
2.必须使用初始化过的变量(调用(ShowNum(ref mNum);)函数之前,必须给传递的参数(mNum)赋值)。

out:

class OutFunc{    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;    }    static void Main(string[] args)    {        int[] myArray = {1,8,3,6,2,5,9,3,0};        int maxIndex;        //The maximum value in myArray is 9        WriteLine($"The maximum value in myArray is         {MaxValue(myArray,out maxIndex)}");        //The first occurrence of this value is at element 7         WriteLine($"The first occurrence of this value is at element        {maxIndex + 1}");    }}

必须在函数调用中使用out关键字。

区别:
1.在函数使用out参数时,必须把它看成未赋值;
2.把未赋值的变量用做ref参数非法,但是可以把未赋值的变量用做out参数。
调用代码可以把已赋值的变量用做out参数,但存储在该变量中的值会在函数执行时丢失。

原创粉丝点击