Why keyword 'this' cannot be used in a sta

2020-02-10 03:30发布

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?

[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?

13条回答
够拽才男人
2楼-- · 2020-02-10 03:59

The short answer for you will be: this refers to an instance of a class which is non existing in a static scope.

But please, look for a good book/class and try to understand basic object oriented concepts before going further on any object oriented programming language.

查看更多
Ridiculous、
3楼-- · 2020-02-10 04:01

this refers to the current instance of a class and can therefore be used only in instance methods. Static methods act on class level, where there are no instances. Hence, no this.

查看更多
叛逆
4楼-- · 2020-02-10 04:04

this is used to refer to the parent object of a variable or method. When you declare static on a method the method can be called without needing to instantiate an object of the class. Therefore the this keyword is not allowed because your static method is not associated with any objects.

查看更多
甜甜的少女心
5楼-- · 2020-02-10 04:05

'this' refers to an instance of a class. Static is initialized without instantiation and hence the static method cannot refer to an 'instance' that is not created.

查看更多
该账号已被封号
6楼-- · 2020-02-10 04:05

I am not sure if this helps your problem, but I believe these two code snippets are equivalent:

MyStaticClass.foo();

and simply

foo();

will both call the foo() method in the MyStaticClass class, assuming you call foo() from inside MyStaticClass

Edit - The easiest way to remember the difference between a static class and a non-static class is to think of something like the Math class in java. You can call Math.abs(x); to get the absolute value of x, and it does not really make sense to instantiate a Math object, which is why Math is a static class.

查看更多
Emotional °昔
7楼-- · 2020-02-10 04:08

this is an instance of the current object. With a static method, there is no current object, and as such, this doesn't exist. It's not really a constraint, but the entire point of a method being static.

查看更多
登录 后发表回答