理解C#參考型別

來源:互聯網
上載者:User

標籤:

掉坑裡了,因為對參考型別的理解不夠深,導致了項目出現了Bug。

首先整理一下C#基礎:參考型別賦值賦的是對象的指標,而實值型別賦值是copy副本,這是參考型別和實值型別的區別之一。

上代碼:

 1  class Program 2     { 3         static void Main(string[] args) 4         { 5             var obj = MyClassA.PropertyA; 6             Console.WriteLine(string.Join(",", MyClassA.PropertyA.Foo)); 7             obj.Foo.RemoveAll(m => m == "e"); 8             Console.WriteLine(string.Join(",",MyClassA.PropertyA.Foo)); 9 10             Console.WriteLine(string.Join(",",MyClassA.PropertyA.Bar));11             obj.Bar = obj.Bar.Where(m => m > 2).ToList();12             Console.WriteLine(string.Join(",", MyClassA.PropertyA.Bar));13 14             obj.Foo = new List<string> {"x", "y", "z"};15             Console.WriteLine(string.Join(",", MyClassA.PropertyA.Foo));16 17             Console.Read();18         }19     }20     class MyClassA21     {22         static MyClassA()23         {24             PropertyA=new MyClassB();25             PropertyA.Foo = new List<string> { "a", "b", "c", "d","e"};26             PropertyA.Bar = new List<int> {1, 2, 3, 4, 5};27         }28         public static MyClassB PropertyA { get; private set; }29     }30 31     class MyClassB32     {33         public List<string> Foo { get; set; }34         public List<int> Bar { get; set; }35     }

不容易理解的是:我明明操作的是obj的內部成員,為什麼連MyClassA.PropertyA的成員值也被改了?

因為,當MyClassA.PropertyA賦值給obj時,obj就指向了MyClassA(參考型別),所以後面只要是對obj成員的操作,其實就是在操作MyCalssA的內部成員。

 

理解C#參考型別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.