C# Value & Reference Type

  • 12321
  • 0
  • C#
  • 2020-06-15

此為個人學習筆記,如果有理解錯誤或是相關資訊歡迎留言告知與分享,謝謝!

參考影片: 小山的 C# 教學

這主要是在討論什麼??

當我們宣告一個物件時,它會在記憶體內(Memory)使用空間

還有其他型別,但這筆記主要討論Value Type & Reference Type

 


主要的差別?

在記憶體中儲存變數的方式不同。

C#中儲存變數的地方在Stack(無論是 Value Type 還是Reference Type )

不同在於存的東西不一樣

 


Value Type 

在Stack中變數儲存的內容是"實值"

Reference Type

在Stack中變數儲存的是"參考"(指向Heap記憶體位址)

而實值是存在Heap

 


Value Type

e.g.,

        int a = 10;

        int b = a;

        b = 20;

        Console.WriteLine("a = " + a + "\nb = " + b);

        Console.ReadKey();

 

 

執行結果

a = 10 

b = 20

 


依序來看,

執行int a時,會在Stack記憶體中佔一個被命名為a的空間 

執行a = 10 時,會將10給予a

執行int b時,同樣在記憶體中佔一個被命名為b的空間

執行b = a;時,會將10賦予b

執行b = 20;時,10將會被20蓋過去

因此印出b時,b=20

 


Reference Type

e.g.,

先加入一個名為Student的Class

    class Student

    {

        public int ID;

        public String Name;



        public string Say()

        {

            return "我的名字叫" + Name + "學號是" + ID;

        }



    }

接著在主要執行程式的地方寫 

   class Program

    {

        static void Main(string[] args)

        {

            Student yui = new Student();

            yui.ID = 123;

            yui.Name = "Yui";



            Student albert = yui;

            albert.Name = "Albert";

            albert.ID = 87;



            Console.WriteLine(yui.Say() + "\n" + albert.Say());

            Console.ReadKey();

        }

    }

 

執行結果

我的名字叫Albert學號是87

我的名字叫Albert學號是87

 


依序來看

            Student yui = new Student();

            yui.ID = 123;

            yui.Name = "Yui";

執行  Student yui = new Student();時,

會在Heap記憶體New一個Student Class的物件

並且將ID = 123 和 Name = "Yui" 存在Heap中

並將在Stack中佔一個被命名為yui的空間

yui的這個空間內存的是Heap記憶體位址

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

            Student albert = yui;

執行 Student albert = yui;時

會在Stack中佔一個被命名為albert的空間

albert = yui;時,則空間內存的值為同樣指向heap的111位址

            albert.Name = "Albert";

            albert.ID = 87;

由上圖可知,目前yui和albert所指到的heap位址是同一個物件

因此當我將Name = "Albert";且ID = 87時

heap位址的內容將被覆蓋掉

所以當我要印出yui和albert物件的Say()時

兩個都會是albert的資訊