C#中使用ref 和 out 的區別

ref測試

一般咱們向方法中傳遞的是值,方法得到的是這些值的一個拷貝,而後使用這些拷貝,當方法運行完畢後,這些拷貝將被丟棄,而原來的值不會受到影響。 這種狀況是一般的,固然還有另一種狀況,咱們向方法傳遞參數的形式,引用(ref)和輸出(out)。spa

有時,咱們須要改變原來變量中的值,這是咱們能夠向方法傳遞變量引用,而不是變量的值,引用是一個變量,他能夠訪問原來變量的值,修改引用將修改原來變量的值。變量的值存儲在內存中,能夠建立一個引用,他指向變量在內存中的位置,當引用被修改時,修改的是內存中的值,所以變量的值能夠被修改,當咱們調用一個含有引用參數的方法時,方法中的參數將指向被傳遞給方法的相應變量,所以,咱們會明白爲何當修改參數變量的修改也將致使原來變量的值被修改。code

建立參數按引用傳遞的方法,需使用關鍵字ref,例:內存

1ci

2it

3table

4class

5變量

6引用

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

using System;

 

class gump

{

    public double Square(ref double x)

    {

        x = x * x;

        return x;

    }

}

class TestApp

{

    public static void Main()

    {

        gump doit = new gump();

        double a = 3;

        double b = 0;

        Console.WriteLine("Before a={0},b={1}",a,b);

        b = doit.Square(ref a);

        Console.WriteLine("After a={0},b={1}", a, b);

        Console.ReadLine();

    }

}

  經過測試咱們發現,變量a的值已經被修改成9 了。

out

經過制定返回類型,能夠從方法返回一個值,有時候,須要返回多個值,雖然咱們可使用ref來完成,可是C#專門提供了一個屬性類型,關鍵字爲out,介紹完後,咱們將說明ref和out的區別。

複製代碼

using System;

class gump
{
    public void math_routines(double x, out double half, out double squared, out double cubed)
    //能夠是:public void math_rotines(//ref double x,out double half,out double squared,out double cubed)
      //可是,不能夠這樣:public void math_routines(out double x,out double half,out double squared,out double cubed)
    //對本例子來講,由於輸出的值要靠X賦值,因此X不能再爲輸出值
    {
        half = x / 2;
        squared = x * x;
        cubed = x * x * x;

    }
}
class TestApp
{
    public static void Main()
    {
        gump doit = new gump();
        double x1 = 600;
        double cubed1 = 0;
        double squared1 = 0;
        double half1 = 0;

        Console.WriteLine("Before method->x1={0}", x1);
        Console.WriteLine("Before method->half1={0}",half1);
        Console.WriteLine("Before method->squared1={0}",squared1);
        Console.WriteLine("Before method->cubed1={0}",cubed1);

        doit.math_routines(x1, out half1, out squared1, out cubed1);

        Console.WriteLine("After method->x1={0}", x1);
        Console.WriteLine("After method->half1={0}", half1);
        Console.WriteLine("After method->squared1={0}", squared1);
        Console.WriteLine("After method->cubed1={0}", cubed1);

        Console.ReadLine();
    }
}

複製代碼

經過使用out關鍵字,咱們改變了三個變量的值,也就是說out是從方法中傳出值

 

咱們發現,ref和out彷佛能夠實現相同的功能,由於均可以改變傳遞到方法中的變量的值,可是兩者本質的區別就是,ref是傳入值,out是傳出值,在含有out關鍵之的方法中,變量 必須有方法參數中不含out(能夠是ref)的變量賦值或者由全局(即方法可使用的該方法外部變量)變量賦值,out的宗旨是保證每個傳出變量都必須被賦值

在傳入變量的時候,out關鍵字的變量能夠不被初始化,可是沒有out 關鍵字的值要被賦值。而ref參數在傳遞給方法是,就已經被賦值了,因此ref側重修改,out側重輸出。

相關文章
相關標籤/搜索