查询.NET中的终结器 [英] Query regarding Finalizers in .NET

查看:79
本文介绍了查询.NET中的终结器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我在终结者上下载了一个点网基础程序示例。我有一个小问题(可能是愚蠢的)。以下是代码:



Hi,

I downloaded a sample dot net basics program on ''finalizers''. I have a small (probably silly) question about that. Here is the code:

using System;
using System.IO;

1. namespace Finalizers
2. {
3.     internal class FileGenerator : IDisposable
4.     {
5.         public FileGenerator()
6.         {
7.         }
8.         ~FileGenerator()
9.         {
10.             // Just a debug output
11.             Console.WriteLine("Closing file!");
12.        }
13.        public void Generate(int Length)
14.        {
15.            // Here some work is done...
16.        }
17.        public void Dispose()
18.        {
19.            // Just a debug output
20.            Console.WriteLine("Disposing object!");
21.        }
22.    }
23.
24.    class Program
25.    {
26.        static void Generate()
27.        {
28.            // Here it would be better to use the C# "using" keyword instead of implicitly calling Dispose!
29.            using (var fGen = new FileGenerator())
30.            {
31.                fGen.Generate(512);
32.                //fGen.Dispose();
33.            }
34.        }
35.        static void Main(string[] args)
36.        {
37.            Generate();
38.            // Here we do some work; simulated by ReadLine statement
39.            Console.Write("Please Press Enter...");
40.            Console.ReadLine();
41.        }
42.    }
43. }





当我评论第32行并执行代码时,仍然是FileGenerator类的Dispose()方法执行,当然要处理掉对象。



但是当我取消注释第32行并执行时,该方法正在执行两次。一旦遇到第32行,接下来当对象被处理掉时。



这是必须的吗?就像在',Dispose()''方法已被称为正确?为什么编译器必须再次调用该方法?



非常感谢您的帮助。



When I comment line number 32 and execute the code, still the Dispose() method of class ''FileGenerator'' is being executed, of course to dispose off the object.

But when I un-comment line number 32 and execute, the method is being executed twice. once when line number 32 is encountered and next when the object is being disposed off.

Is this the way it has to be? As in, the ''Dispose()'' method is already called right? Why does the compiler have to call the method again?

Thanks a lot for your help.

推荐答案

当您使用语句使用时,表示该变量会自动放置在块的末尾。



因此,如果你自己调用Dispose()方法,它会被执行两次。



你不需要在一个<中显式调用Dispose()方法code>使用
block。
When you use using statement, it means that the variable is automatically disposed at the end of the block.

So if you call the Dispose() method by yourself, it is executed twice.

You don''t need to explicitly call Dispose() method in a using block.


这篇关于查询.NET中的终结器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆