在c#中ref 和 out关键字的联系和区别

联系

out:输出参数;ref:引用参数;
两者都是按地址传递的,使用后都将改变原来参数的数值,且使用方式几乎相同,即在函数定义和函数调用中用作参数的修饰符,实际上,out的执行方式与引用参数几乎完全一样,因为在函数执行完毕后,该参数的值将返回给函数调用中使用的变量。

区别

  • 把未赋值的变量用作ref参数是非法的,但可以把未赋值的变量用out参数。
  • 另外, 在参数中使用out参数时候,必须把它看成尚未赋值。如果想让一个方法返回多个值可以用out参数来处理,即调用代码可以把已经赋值的变量用作out参数,但存储在该变量中的值会在函数执行时丢失。

ref实例

交换两个数
namespace lesson1
{
    public class myClass
    {
        public void swap (ref int a, ref int b)
        {
            int temp = a;
            a = b;
            b = temp;
        }
    }


    class MainClass
    {
        public static void Main (string[] args)
        {

            myClass c = new myClass ();
            Console.WriteLine (c.sum (3, 5));
            int i = 5;
            int j = 12;
            c.swap (ref i, ref j);
            Console.WriteLine ("i= " + i + " j = " + j);
        }
    }
}

out实例

确定数组中第一个出现最大值的位置
namespace lesson1
{
    class MainClass
    {
        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;
        }

        public static void Main (string[] args)
        {
            int[] myArray = { 1, 8, 3, 6, 2, 5, 9, 3, 0, 2 };
            int maxIndex;
            Console.WriteLine ("max is " + MaxValue (myArray, out maxIndex));
            int first = maxIndex + 1;
            Console.WriteLine ("第一个出现最大值的位置是" + first);

        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值