C#词典是否仅存储对象的引用或作为键添加的对象的完整副本? [英] Does C# dictionary store only the reference of the object or the full copy of the object which is added as key?

查看:45
本文介绍了C#词典是否仅存储对象的引用或作为键添加的对象的完整副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个类用作字典的键.但是就内存消耗而言,该类很大.因此,我想知道,当我们将对象添加为字典的键时,它只是添加其引用还是添加了完整副本.这样,如果添加了对象的完整副本,那么我就可以使用对象的哈希码.

I want to use a class as key for a dictionary. But the class is large in terms of memory consumption. So, I want to know that when we add an object as key to dictionary, does it only add its reference or full copy is added. As, if the full copy of the object is added then I can just use the hashcode of the object.

推荐答案

词典存储传递的任何值-键和条目的值都是这种情况.对于引用类型,该值是一个引用-无需克隆即可复制该引用所引用的对象.这是一个示例:

The dictionary stores whatever value is passed in - that's the case for both the key and the value of the entry. For reference types, that value is a reference - there's no cloning involved to copy the object that the reference refers to. Here's an example:

var dictionary = new Dictionary<int, StringBuilder>();
var builder = new StringBuilder("x");
dictionary.Add(5, builder);

// Retrieve the reference from the dictionary and append to it
dictionary[5].Append("y");

Console.WriteLine(builder); // Prints xy

这表明事物的 value 方面.密钥以相同的方式存储(作为参考),但是这里有一个警告……如果您更改密钥所指的对象,那么从根本上说,在大多数情况下,这将破坏字典,因为密钥是哈希码在添加条目时进行计算.通常,您将不可变类型(例如 string )用作字典的键.

That's showing the value side of things. The key is stored in the same way - as a reference - but there's a caveat here... if you mutate the object that a key refers to, that's fundamentally going to break the dictionary in most cases, as the hash code of the key is computed when the entry is added. Typically you use immutable types (like string) as keys for dictionaries.

这篇关于C#词典是否仅存储对象的引用或作为键添加的对象的完整副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆