C# .NET:字典值是按引用还是值存储

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13058944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:30:58  来源:igfitidea点击:

.NET: Are Dictionary values stored by reference or value

c#.netdictionaryreference-type

提问by NSjonas

I have a Dictionary<int, Product>. 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 reference to the original object?

我有一个Dictionary<int, Product>. 如果将同一个 Product 添加到多个键,是否为每个键存储该对象的新实例?或者只是对原始对象的引用?

This collection is very large and each product will have between 1-10 Keys to it. My primary concern is memory allocation.

这个集合非常大,每个产品都有 1-10 个密钥。我主要关心的是内存分配。

采纳答案by zmbq

If Product is a reference type (class and not struct), only a reference will be stored.

如果 Product 是引用类型(类而不是结构),则只会存储引用。

回答by Chris Doggett

No, it should use the same reference to the original object.

不,它应该使用对原始对象的相同引用。

I'm not entirely certain how it will behave if the Dictionary is serialized/deserialized, however.

但是,如果字典被序列化/反序列化,我并不完全确定它的行为。

回答by aiodintsov

reference types are stored as references always. no one is going to guess what "clone" logic you intend for your type. if you need copies, you will have to create them on your own before placing to containers, passing to other functions and so on.

引用类型总是作为引用存储。没有人会猜测您打算为您的类型使用什么“克隆”逻辑。如果您需要副本,则必须在放置到容器、传递给其他函数等之前自己创建它们。

value types are copied (simplistically byte representation copy is created, however all reference values will still be references), unless passed as ref to functions. for containers though they will be copies. unless you create a reference type wrapper for them.

值类型被复制(简单地创建字节表示副本,但是所有引用值仍然是引用),除非作为 ref 传递给函数。对于容器,尽管它们将是副本。除非您为它们创建引用类型包装器。

回答by Servy

THe Dictionarywill story 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.

Dictionary会的故事,你通过它的键的值的副本。它或任何其他集合/容器都无法存储对任何值的引用,因为容器可能比您尝试存储在其中的变量寿命更长。现在,正如其他人所说,如果值的类型是引用类型,则变量的值只是一个引用,因此您只需存储对变量的引用的副本。如果字典值的类型是值类型,则将复制实际值。