gpt4 book ai didi

c# - "this"关键字可以与值类型一起使用吗?

转载 作者:太空狗 更新时间:2023-10-29 21:03:44 26 4
gpt4 key购买 nike

在 .NET Reflector 中查看 Int32.GetHashCode() 的反汇编代码时,我注意到“this”关键字的有趣用法:

public override int GetHashCode()
{
return this;
}

我一直认为“this”只用于引用类型而不是值类型。在上面的代码中,每次尝试获取 int 的哈希码时都会使用装箱吗?

来自 MSDN 中“this”关键字的文档:- this 关键字引用类的当前实例

问候

最佳答案

是的,this 对值类型有效。它不会导致拳击。虽然它引用值类型,但它不是与引用类型引用相同的引用 - 它是编译/开发时的便利而不是运行时引用。

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.

关于c# - "this"关键字可以与值类型一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/562749/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com