[英]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>
那么在调用Equals
时IEquatable<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.