当对象引用其实现的接口时,该对象还会存在吗?
我有一个实现接口的类。我不需要对该类的对象的引用 - 只需引用它们的接口。看起来像:
interface A {}
class B : A {}
//in code:
A a = (A) new B();
我的问题是:当我引用 B 的 A 时,B 的实例是否会存在(不被 GC 收集)?
I have a class implementing an interface. I don't need a reference to objects of that class - only reference to their interfaces. It looks like:
interface A {}
class B : A {}
//in code:
A a = (A) new B();
My question is: Will instance of B to live (not collecting by GC) while I have a reference to A of that B?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,因为尽管您只能看到实现该接口
A
的部分,但您仍然拥有对该new B()
的引用。Yes, because you still have a reference to that
new B()
although you can see only the part that implements that interfaceA
.无论变量的类型是类还是接口,引用都是相同的实际值。所以是的:它会继续存在。
The reference is the same actual value no matter whether your variable is typed as the class or the interface. So yes: it will stay alive.
是的,对象的实例是相同的,您可以将对象强制转换为其实现的任何接口,但实例是一个。
yes the instance of the object is the same, you can cast the object to any of its implemented interface, but the instance is one.
是的,因为通过接口对对象的引用仍然是对该对象的引用。
将对象转换为接口不会创建新对象,它只是改变您用来与对象通信的“门户”。
您可以在 LINQPad 中轻松测试:
执行时,您将得到:
然后,可选:
但请注意,B 在整个 GC 周期中幸存下来,即使您通过 A 引用了它。
Yes, because a reference to an object through an interface is still a reference to that object.
Casting an object to an interface does not create a new object, it just alters the "portal" you use to talk to the object through.
You can easily test this in LINQPad:
When executed, you'll get:
And then, optionally:
But notice that B survived the full GC cycle, even though you had a reference to it through A.