c# - 为什么不能在静态方法中使用关键字 'this'?

标签 c# this static-members

为什么不能在静态方法中使用关键字this?我想知道为什么 C# 定义了这个约束。这种约束可以获得什么好处?

[更新]: 实际上,这是我在面试中得到的一个问题。 我确实知道“static”和“this”的用法,根据您的所有回复,我想我知道为什么两者不能一起使用。也就是说,静态方法用于改变状态或在类型级别做某事,但是当你需要使用'this'时意味着你想改变状态或在实例级别做某事。为了区分类型的状态变化和实例的状态变化,c#不允许在静态方法中使用'this'。我说得对吗?

最佳答案

因为 this 指向类的一个实例,所以在静态方法中你没有实例。

The this keyword refers to the current instance of the class. Static member functions do not have a this pointer

你会注意到静态成员的定义是

Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object

这就是为什么 this 没有指向的原因。

关于c# - 为什么不能在静态方法中使用关键字 'this'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3459282/

相关文章:

c# - UWP MVVM 模板 10 : Access single instance of external API across application

c# - 如何使用 C# 在 Windows 窗体中显示 MSSQL 中的实时查询统计启用的执行查询百分比?

javascript为添加到类的方法设置 "this"

javascript - 为什么括号在函数调用中更改为 `this`

javascript - 将 React prop 传递到 axios.post 时如何绑定(bind) "this"

java - 为什么不在 LinkedList 中定义 ListIterator 的静态类?

c++ - 静态变量初始化测验

c# - Int 和 Int 的 FirstOrDefault 行为?

c# - Mono for Android 是如何工作的以及 C# 和 Dalvik 之间的关系是什么?

java - 什么是正确的单例实现以及为什么