在C#是什么析构函数和类Finalize方法之间的区别? [英] In C# what is the difference between a destructor and a Finalize method in a class?
问题描述
有什么区别,如果有,析构函数和类Finalize方法的?
我最近发现,Visual Studio 2008中认为代名词Finalize方法析构函数,这意味着Visual Studio将不会让你同时在一个类中定义了这两种方法。
例如,下面的code片段:
类TestFinalize
{
〜TestFinalize()
{
敲定();
} 公共BOOL敲定()
{
返回true;
}
}
给出的呼叫下面的错误在析构函数来完成:
在调用以下方法或属性之间暧昧:
TestFinalize。〜TestFinalize()'和'TestFinalize.Finalize()
块引用>如果最终确定的呼叫已被注释掉,它提供了以下错误:
键入ManagementConcepts.Service.TestFinalize'已经定义了一个名为成员
终结具有相同的参数类型
块引用>解决方案在C#重写析构函数
System.Object.Finalize
方法。您必须使用析构函数语法这样做。手动覆盖敲定
会给你一个错误消息。基本上你想用你的
敲定
方法声明做什么是的 隐藏 基类的方法。它会导致编译器发出这可以使用新
修改(如果是去上班)保持沉默的警告。这里要注意的重要一点是,您不能两个覆盖
并声明新
成员具有相同的名称在这样既具有析构函数和敲定
方法将导致错误的同时(但您可以,虽然没有推荐,申报公开新无效的Finalize()
方法,如果你不声明析构函数)。What is the difference, if there is one, between a destructor and a Finalize method in a class?
I recently discovered that Visual Studio 2008 considers a destructor synonymous with a Finalize method, meaning that Visual Studio won't let you simultaneously define both methods in a class.
For example, the following code fragment:
class TestFinalize { ~TestFinalize() { Finalize(); } public bool Finalize() { return true; } }
Gives the following error on the call to Finalize in the destructor:
The call is ambiguous between the following methods or properties: 'TestFinalize.~TestFinalize()' and 'TestFinalize.Finalize()'
And if the call to Finalize is commented out, it gives the following error:
Type 'ManagementConcepts.Service.TestFinalize' already defines a member called 'Finalize' with the same parameter types
解决方案A destructor in C# overrides
System.Object.Finalize
method. You have to use destructor syntax to do so. Manually overridingFinalize
will give you an error message.Basically what you trying to do with your
Finalize
method declaration is hiding the method of the base class. It will cause the compiler to issue a warning which can be silenced using thenew
modifier (if it was going to work). The important thing to note here is that you can't bothoverride
and declare anew
member with identical name at the same time so having both a destructor and aFinalize
method will result in an error (but you can, although not recommended, declare apublic new void Finalize()
method if you're not declaring a destructor).这篇关于在C#是什么析构函数和类Finalize方法之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!