为什么我可以创建一个类的实例,而不存储到一个变量,仍然有一切工作? [英] Why can I create an instance of a class without storing it to a variable and still have everything work?

查看:94
本文介绍了为什么我可以创建一个类的实例,而不存储到一个变量,仍然有一切工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非静态类 ImplementHeaderButtons ,它包含一个非静态的公共方法 Implement 。类和方法的名称不重要,重要的是它们不是静态的,因此它们需要被实例化以便使用,是吗?

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?

我曾经这样做:

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如果它不按预期工作,就会感到惊讶,但它确实如此。

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

推荐答案


不是静态的,所以他们需要被实例化以便使用,是吗?

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

是的,但你仍然实例化类用 new ImplementHeaderButtons(),你只是不在任何地方存储对新创建的实例的引用。

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).

这篇关于为什么我可以创建一个类的实例,而不存储到一个变量,仍然有一切工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆