System.Object 类中的 Finalize 方法
出于好奇,我反汇编了 mscorlib.dll 以检查 System.Object 类的实现。
我发现了一些奇怪的东西。
1).
public class Object {
...
protected override void Finalize(){}
...
}
为什么基类中有重写方法?
2) public class Employee {
public void InstanceMethod() {
this.Finalize();
//Does not compile, can i not access protected methods of base class??
}
}
我只是想知道 Object 类中“受保护的 Finalize”方法有什么用以及为什么编译器会对其进行特殊处理?
Out of curiosity i disassembled mscorlib.dll to check the implementation of System.Object class.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是 Reflector 中的一个错误,它会被虚拟但没有“newslot”属性并且没有基类类型的方法混淆。当你将反编译器切换到IL时可能会更容易看到。
终结器的真实声明(从参考源复制而来)与您所期望的一样:
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. It might be easier to see when you switch the decompiler to IL.
The real declaration of the finalizer, as copied from the Reference Source, is much as you'd expect it to be:
对于第二个问题,C#的
~MyClass
在VB.NET中编写为Protected Overrides Sub Finalize()
,相当于protected override Finalize()
>。所以这只是 C# 语法的差异。对于第一个问题,在 Reflector 中,
与被覆盖的虚拟成员相比,它缺少通常在新虚拟成员上看到的
newslot
属性。For the second question, C#'s
~MyClass
is written in VB.NET asProtected Overrides Sub Finalize()
which is equivalent toprotected override Finalize()
. So it is just C# syntax difference.For the first question, in Reflector it is
which is missing
newslot
attribute generally seen on new virtual members as compared to overridden.查看 MSDN 中的 Object.Finalize:
因此,您的问题的答案是:嗯 - 这是 CLR 内部的一部分; C# 编译器会完成编写时所需的所有工作,例如:
Check out the MSDN to Object.Finalize:
Therefore, an answer to your question would be: Well - that's part of the internals of the CLR; the C# compiler does all the work required when writing for example: