当对象引用其实现的接口时,该对象还会存在吗?

发布于 2024-12-07 15:21:00 字数 186 浏览 0 评论 0原文

我有一个实现接口的类。我不需要对该类的对象的引用 - 只需引用它们的接口。看起来像:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

又怨 2024-12-14 15:21:00

是的,因为尽管您只能看到实现该接口 A 的部分,但您仍然拥有对该 new B() 的引用。

Yes, because you still have a reference to that new B() although you can see only the part that implements that interface A.

我是男神闪亮亮 2024-12-14 15:21:00

无论变量的类型是类还是接口,引用都是相同的实际值。所以是的:它会继续存在。

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.

潜移默化 2024-12-14 15:21:00

是的,对象的实例是相同的,您可以将对象强制转换为其实现的任何接口,但实例是一个。

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.

桃酥萝莉 2024-12-14 15:21:00

是的,因为通过接口对对象的引用仍然是对该对象的引用。

将对象转换为接口不会创建新对象,它只是改变您用来与对象通信的“门户”。

您可以在 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");
    }
}

执行时,您将得到:

到了

然后,可选:

B已最终确定

但请注意,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:

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

But notice that B survived the full GC cycle, even though you had a reference to it through A.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文