终结器调用静态方法

终结器调用静态方法

本文介绍了从C#终结器调用静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

杰弗里·里希特(Jeffrey Richter)通过C#书在其CLR中(如示例章节使用需要特殊清除的类型)表示以下内容:

Jeffrey Richter in his CLR via C# book (as seen online in the sample chapter Working with Types Requiring Special Cleanup) indicates the following:

我从上面的引文中了解了所有内容,但是句子以粗体显示.如果静态方法只能使用其他引用由于其生命周期而无法最终确定的对象的静态成员,那么该方法如何在内部使用最终完成的对象?为什么调用实例方法安全?抱歉,我的结论可能是错误的,所以感谢您对此问题的任何解释.预先感谢.

I understand everything from the quote above, but the sentence which is in bold. How can a static method use finalized object internally if it can use only other static-members which reference to objects that can't be finalized because of their lifetime and why is it safe to call instance methods? Sorry, I may be wrong in my conclusions, so I'd be grateful for any explanations of the question. Thanks in advance.

推荐答案

例如,我们有两个类:

sealed class B
{
    private A _a = new A();

    ~B()
    {
        B.ManipulateA(_a);
    }

    public static void ManipulateA(A a)
    {
        //manipulations with "A" object
    }
}

sealed class A
{
    ~A() { }
}

因此,如果 CLR不能对Finalize方法的调用顺序做任何保证,则应从 B Finalizer中删除对静态方法的调用,因为 A 对象可以在调用 B Finalizer时已经完成,而 ManipulateA 可以尝试访问完成后的对象.

So if CLR doesn’t make any guarantees as to the order in which Finalize methods are called, we should delete call to static method from B Finalizer, because our A object can be finalized already at the time when B Finalizer is called, and ManipulateA can try to access finalized object.

我认为Jeffrey谈论的是这个例子.

I think Jeffrey talks about something like this example.

这篇关于从C#终结器调用静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 14:26