问题描述
为什么不能关键字这个
将在静态方法中使用吗?我很奇怪,为什么C#定义了这个限制。 ?有什么好处可以通过这个约束来获得
Why can't the keyword this
be used in a static method? I am wondering why C# defines this constraint. What benefits can be gained by this constraint?
[更新]:
其实,这是我在接受采访时有一个问题。
我知道的静态和本的使用,基于所有您的回复,我想我知道一点点,为什么两者不能同时使用。也就是说,对于静态方法是用来改变的状态还是在类型层次的东西,但是当你需要使用'这'意味着你要改变状态或者做一下实例级。为了区分类型和实例的状态变化的状态变化,那么C#允许DONOT'这'在静态方法中使用。我说得对不对?
[Update]:Actually, this is a question I got in an interview. I do know the usage of 'static' and 'this', based on all your response, I guess I know a little of why the two can not be used together. That is, for static method is used to changed state or do something in a type level, but when you need to use 'this' means you want to change the state or do something in a instance level. In order to differentiate the state change of a type and the state change of an instance, then c# donot allow use 'this' in a static method. Am I right?
推荐答案
由于这个
指向的一个实例类,在静态方法你没有一个实例。
Because this
points to an instance of the class, in the static method you don't have an instance.
的
您会注意到的定义静态成员
You'll notice the definition of a static member is
的
这就是为什么这个
没有任何指向。
Which is why this
has nothing to point to.
这篇关于为什么关键字'这个'不能在静态方法中使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!