简体   繁体   English

在System.Object类中的Finalize方法

[英]Finalize method in System.Object class

Out of curiosity i disassembled mscorlib.dll to check the implementation of System.Object class. 出于好奇,我反汇编了mscorlib.dll以检查System.Object类的实现。

I found something weird in that. 我发现了一些奇怪的东西。

1).    
public class Object {
...
    protected override void Finalize(){}
...
}

How come a base class has an overriden method in it? 为什么基类中有覆盖方法呢?

2) public class Employee {
            public void InstanceMethod() {
                this.Finalize();
                //Does not compile, can i not access protected methods of base class??
            }
        }

I am just wondering what's the use of "protected Finalize" method in Object class and why it has got special treatment by compiler? 我只是想知道在Object类中使用“protected Finalize”方法是什么以及为什么它被编译器特殊处理?

It is a bug in Reflector, it gets confused by a method that's virtual but doesn't have the "newslot" attribute and doesn't have a base class type. 这是Reflector中的一个错误,它被一个虚拟但没有“newslot”属性并且没有基类类型的方法搞糊涂了。 It might be easier to see when you switch the decompiler to IL. 将反编译器切换到IL时可能更容易看到。

The real declaration of the finalizer, as copied from the Reference Source, is much as you'd expect it to be: 从参考源复制的终结器的真实声明与您期望的一样:

// Allow an object to free resources before the object is reclaimed by the GC.
//
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
~Object()
{
}

For the second question, C#'s ~MyClass is written in VB.NET as Protected Overrides Sub Finalize() which is equivalent to protected override Finalize() . 对于第二个问题,C#的~MyClass是用VB.NET编写的Protected Overrides Sub Finalize() ,相当于protected override Finalize() So it is just C# syntax difference. 所以这只是C#语法的区别。

For the first question, in Reflector it is 对于第一个问题,在Reflector中它是

.method family hidebysig virtual instance void Finalize() cil managed

which is missing newslot attribute generally seen on new virtual members as compared to overridden. 通常在新虚拟成员上看到的缺少newslot属性与被覆盖的相比。

Check out the MSDN to Object.Finalize : 查看MSDN到Object.Finalize

Destructors are the C# mechanism for performing cleanup operations. 析构函数是执行清理操作的C#机制。 Destructors provide appropriate safeguards, such as automatically calling the base type's destructor. 析构函数提供适当的安全措施,例如自动调用基类型的析构函数。 In C# code, Object.Finalize cannot be called or overridden. 在C#代码中,无法调用或覆盖Object.Finalize。

Therefore, an answer to your question would be: Well - that's part of the internals of the CLR; 因此,你的问题的答案是:嗯 - 这是CLR内部的一部分; the C# compiler does all the work required when writing for example: 例如,C#编译器完成编写时所需的所有工作:

public class Employee
{
   //Finalizer, also known as "destructor"
   ~Employee()
   {

   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM