ref关键字的作用

ref关键字使参数按引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。

就是说,在调用方法的参数中使用ref关键字可以使得变量能够改变。

ref和out都是引用地址
ref可以理解为引用传值,一个构造器或方法里含有ref参数,任何使用这个构造器或方法的地方操纵的都是同一个变量,ref所修饰的变量,也就是说.和你定义全局变量或者static变量差不多的[效果]。

以下是一个使用ref和不使用的区别。

不使用:委托在前面讲了

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
    delegate void printFunction( int x);
    class Program
    {
        public void add1( int x)
        { x += 2; }
        public void add2( int x)
        { x += 3; }
        static void Main(string[] args)
        {
            Program pm = new Program();
            printFunction p = pm.add1; //建立委托
            p += pm.add2;
            p += pm.add1;

            int x = 5;

            p( x); //这里才真正传值,把x传递过去,前面只是给定义,并且通过调用方法改变x的值。

            Console.WriteLine("{0}",x);
            Console.ReadLine();
        }
    }
}

结果:

5
这里没有对x的值发生改变。

使用ref关键字:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
    delegate void printFunction(ref int x);
    class Program
    {
        public void add1(ref int x)
        { x += 2; }
        public void add2(ref int x)
        { x += 3; }
        static void Main(string[] args)
        {
            Program pm = new Program();
            printFunction p = pm.add1;
            p += pm.add2;
            p += pm.add1;

            int x = 5;

            p(ref x); //这里才真正传值,把x传递过去,前面只是给定义,并且通过调用方法改变x的值。

            Console.WriteLine("{0}",x);
            Console.ReadLine();
        }
    }
}

结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值