C# dictionary value clearing out when I clear list previously assigned to it…why?

后端 未结 6 498
北恋
北恋 2020-11-30 13:25
Dictionary > saleItemNew = new Dictionary> ();

saleItems = new List  ();
         


        
6条回答
  •  独厮守ぢ
    2020-11-30 14:02

    The reason is that Dictionary is a reference and not a value type. When you assign a Dictionary to another variable it does not perform a deep copy. Instead it just points another reference at the same object. Since there is only one object, clearing via either reference will be visible to both references.

    This in contrast to value types in the .Net Framework. Assignment of a value type essentially performs a shallow copy of the data and creates two independent objects. Note, that if the value type has a reference field, the two field in the two value types will still point to the same object.

提交回复
热议问题