简体   繁体   English

当用作字典中的键时,是否会覆盖结构导致装箱的GetHashCode?

[英]Will overriding GetHashCode for a struct cause boxing when used as a key in a dictionary?

Normally if a struct implements an interface, assigning such struct to an interface variable causes boxing, eg: 通常,如果结构实现了接口,则将此类结构分配给接口变量会导致装箱,例如:

interface IFoo {}

struct S : IFoo {}

S s = ...
IFoo f = s; // boxing here

However there are exceptions. 但也有例外。 It appears that implementing IEquatable<T> and using such struct in dictionary as a key, won't cause boxing. 似乎实现IEquatable<T>并在字典中使用这样的结构作为键,不会导致装箱。 So the question is then, what if I just override GetHashCode without implementing IEquatable<T> ? 那么问题是,如果我只是覆盖GetHashCode而不实现IEquatable<T>怎么办? Will it fall into some special case? 它会陷入某种特殊情况吗?

If you don't implement IEquatable<T> then the struct will be boxed when calling Equals . 如果你没有实现IEquatable<T>那么在调用EqualsIEquatable<T>将被装箱。 Equals is a virtual method and therefore requires a reference to obtain the associated method table. Equals是一个虚方法,因此需要引用来获取关联的方法表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 覆盖类上的GetHashCode和Equals,因为它在字典中使用 - Overriding GetHashCode and Equals on a class because it's used in a dictionary 不调用以元组为键的字典 GetHashCode - Dictionary with Tuple as Key GetHashCode is not called 如何实现 Struct 用作字典键 - How to implement Struct to be used as Dictionary key 重写GetHashCode()时使用Guid()。GetHashCode()有什么缺点 - What are the drawbacks of using a Guid().GetHashCode() when overriding GetHashCode() 覆盖GetHashCode() - Overriding GetHashCode() 在WPF中,当与值类型一起使用时,DependencyProperty会导致大量的装箱/拆箱吗? - In WPF do DependencyProperty's cause lots of boxing/unboxing when used with value types? 实现了GetHashCode但是Dictionary无法找到密钥? - GetHashCode is implemented but Dictionary is unable to find the key? 我应该何时在不可变结构上实现GetHashCode? - When should I implement GetHashCode on an immutable struct? 当类实现Equals和GetHashCode时,如何将对象引用用作C#字典中的键? - How do you use an object reference as a key in a C# dictionary when the class implements Equals and GetHashCode? 自定义GetHashcode实现是否会导致Dictionary或Hashtable的“桶”出现问题 - Can a custom GetHashcode implementation cause problems with Dictionary or Hashtable's “buckets”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM