.NET: Are Dictionary values stored by reference or value

前端 未结 4 500
我在风中等你
我在风中等你 2021-02-07 02:14

I have a Dictionary. If the same Product is added to more than one key is an new instance of that object stored for each key? Or just a refere

4条回答
  •  别跟我提以往
    2021-02-07 03:05

    The Dictionary will store a copy of the the value of the key that you pass it. It wouldn't be possible for it, or any other collection/container for that matter, to store a reference to any value as it is possible for the container to outlive the variable that you tried to store in it.

    Now, as others have said, if the type of the value is a reference type, the value of the variable is just a reference, so you're just storing a copy of the reference to the variable. If the Type of the value of the dictionary is a value type then the actual value will be copied.

提交回复
热议问题