Why can I create an instance of a class without st

2020-04-08 09:05发布

I have a non-static class called ImplementHeaderButtons which contains a non-static public method called Implement. The name of the class and method are not important, what's important is that they are not static, so they need to be instantiated in order to be used, right?

So I used to do this:

var implementHeaderButtons = new ImplementHeaderButtons();
implementHeaderButtons.Implement(this, headerButtons);

But then I decided to play around a bit with it (actually I was looking for a way to make it a one-liner) and I concluded that the following code works just as well:

new ImplementHeaderButtons().Implement(this, headerButtons);

Now, I do not need a variable to hold the instance, but my question is: how come I can create a new instance of a class on the fly and call a method of it without having a variable to store the instance?

I wouldn't be surprised if it didn't work as intended, but it does.

3条回答
太酷不给撩
2楼-- · 2020-04-08 09:24

they are not static, so they need to be instantiated in order to be used, right?

Yes, but you are still instantiating the class with new ImplementHeaderButtons(), you just aren't storing a reference to that newly created instance anywhere.

You can still call a method on this instance as you have done in your example, but you will not be able to do anything else with it afterwards without a reference. Eventually the instance will be cleaned up by the garbage collector (provided the method you call does not store a reference to the object somewhere).

查看更多
神经病院院长
3楼-- · 2020-04-08 09:29

A variable is just a reference, for your convenience. You are not naming it, but it is just there, on the top of the stack (in general ;-) ). Do you can call it's methods as long as you can refer to the variable, either by using it's name (which you do not have) or by working on the "unnamed" object you've just created.

查看更多
唯我独甜
4楼-- · 2020-04-08 09:39

Your call to new ImplementHeaderButtons() returns an instance of ImplementHeaderButtons. Then, you call .Implement() on that instance.

Think of it like this:

(new ImplementHeaderButtons()).Implement(this, headerButtons);
查看更多
登录 后发表回答