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

标签 c# .net

在 .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/

相关文章:

c# - 在 C# 中重写基类的 Json.NET 注解

c# - 如何更改 SQL 中存储过程的排序规则?

c# - 如何使用 Xaml 将列表绑定(bind)到 WPF TreeView ?

C# InvokeRequired 与属性 getter

.net - .NET 的智能卡身份验证

.net - 如何在设计时设置控件的父级

c# - C#中如何获取字符的ASCII值

java - 为 SVN 和 CVS 提供通用接口(interface)

.net - .NET 中固定宽度处理的最佳实践

c# - 如何从另一个项目访问连接字符串