我在.NET Reflector中查看Int32.GetHashCode()的反汇编代码时注意到了这个有趣的“this”关键字:
public override int GetHashCode() { return this; }
我一直认为“this”仅用于引用类型而不是值类型.在上面的代码中,每次尝试获取int的哈希码时都会使用装箱吗?
从MSDN中“this”关键字的文档:
– this关键字引用类的当前实例
问候
解决方法
是的,这对值类型有效.它不会导致拳击.虽然它引用了value-type,但它不是引用与引用类型引用相同的 – 它是编译/开发时间的便利而不是运行时引用.
C#规范的第7.5.7节规定:
- When this is used in a
primary-expression within an instance
constructor of a struct,it is
classified as a variable. The type of
the variable is the instance type
(§10.3.1) of the struct within which
the usage occurs,and the variable
represents the struct being
constructed. The this variable of an
instance constructor of a struct
behaves exactly the same as an out
parameter of the struct type—in
particular,this means that the
variable must be definitely assigned
in every execution path of the
instance constructor.- When this is
used in a primary-expression within an
instance method or instance accessor
of a struct,it is classified as a
variable. The type of the variable is
the instance type (§10.3.1) of the
struct within which the usage occurs.
- If the method or accessor is not an
iterator (§10.14),the this variable
represents the struct for which the
method or accessor was invoked,and
behaves exactly the same as a ref
parameter of the struct type.
- If the method or accessor is an iterator,the this variable represents a copy of the struct for which the method or accessor was invoked,and behaves exactly the same as a value parameter of the struct type.