[英]Will an object live while there is reference to interface which It implements?
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? 我的问题是:当我引用该B的A时,该B的实例是否可以存在(不通过GC收集)?
是的,因为尽管您只能看到实现该接口A
的部分,但是您仍然可以引用该new B()
。
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, 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 : 您可以在LINQPad中轻松进行测试:
void Main()
{
A a = (A)new B();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.KeepAlive(a);
Debug.WriteLine("Got here");
}
public interface A
{
}
public class B : A
{
~B()
{
Debug.WriteLine("B was finalized");
}
}
When executed, you'll get: 执行后,您将获得:
Got here 去那里
And then, optionally: 然后,可选地:
B was finalized B已完成
But notice that B survived the full GC cycle, even though you had a reference to it through A. 但是请注意,即使您通过A引用了B,B仍然可以在整个GC周期中幸免。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.