• 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();
            }
        }
    }

    结果:

  • 相关阅读:
    浮点数二分
    [模板]整数二分
    Mybatis实现增删改查
    如何使用 KEIL 下载 HEX 文件?
    线程CPU使用率该如何计算?
    单片机里面的CPU使用率是什么鬼?
    ASP.NET Core 3.1使用JWT认证Token授权 以及刷新Token
    ASP.NET Core 3.1使用Swagger API接口文档
    Visual Studio 默认git拉取Github出错 No error could not read Username for 'https://github.com': terminal prompts disabled
    ASP.NET Core 3.1使用log4net/nlog/Serilog记录日志
  • 原文地址:https://www.cnblogs.com/alsf/p/5941514.html
Copyright © 2020-2023  润新知