zoukankan      html  css  js  c++  java
  • 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();
            }
        }
    }

    结果:

  • 相关阅读:
    电子书下载:Pro jQuery
    神鬼传奇小技巧:教你如何修改自己想要的时装
    用虚拟机玩游戏的方法!! 开3D加速!
    如何让DevExpress的DateEdit控件正确显示日期的周名
    SOAP Version 1.2
    Delphi中的容器类
    <神鬼传奇>客户端终极优化精简方法
    今日阅读20090102基本数据结构
    判断一个char[]里是否包含两个连续的\r\n
    蛙蛙推荐:改进同步等待的网络服务端应用
  • 原文地址:https://www.cnblogs.com/alsf/p/5941514.html
Copyright © 2011-2022 走看看