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

結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM