为什么要使用用在C#中的IDisposable的呢?要使、IDisposable

2023-09-03 03:05:32 作者:穩拿情場我稱王

今天,我想用一个文件执行的操作,所以我想出了这个code

Today, I wanted to perform an operation with a file so I came up with this code

    class Test1
    {
        Test1()
        {
            using (var fileStream = new FileStream("c:\\test.txt", FileMode.Open))
            {
                //just use this filestream in a using Statement and release it after use. 
            }
        }
    }

但在code的审查,我被要求实现IDisposable接口和释放方法

But on code review, I was asked to implement IDisposable interface and Finalizer methods

    class Test : IDisposable
    {
        Test()
        {
            //using some un managed resources like files or database connections.
        }

        ~Test()
        {
            //since .NET garbage collector, does not call Dispose method, i call in Finalize method since .net garbage collector calls this
        }

        public void Dispose()
        {
            //release my files or database connections
        }
    }

不过,我的问题是,为什么要这样呢?

But, my question is why should I ?

虽然根据我,我不能证明我的方法,我们为什么要使用的IDisposable 在使用语句本身可以释放资源)

Although I cannot justify my methodology according to me, why should we use IDisposable when using statement can itself release resources)

任何特定的优势或正在丢失一些东西呢?

Any specific advantages or am is missing something here?

推荐答案

由没有人给出的答案是使用块仅可用于类是正确的实现了的IDisposable 接口,并解释这是完美的。从你的身边的问题是:为什么我需要添加IDisposable接口的测试类但在code的审查,我被要求实现IDisposable接口和测试类释放方法。 答案很简单 1)由于每编码标准,其次是这么多的开发商这是一件好事落实的IDisposable 上使用的一些资源,一旦该对象的范围是在类处置方法的类将确保所有资源都被释放。 2)已写入的类是从未使得在将来就不会发生变制成,如果这样的变化是由与新资源添加然后显影剂知道他必须释放这些资源在处置功能。

The answer given by "No One" is correct that using block can only be used for the classes that implement the IDisposable interface and explanation for it is perfect. The question from your side is "Why I need to add IDisposable on Test class and But on code review, I was asked to implement IDisposable interface and Finalizer methods on Test class." The answer is simple 1) As the per the coding standards followed by so many developers it is always good to implement IDisposable on the classes which use some resources and once the scope of that object is over the Dispose method in that class will make sure all the resources have been released. 2) The class that has been written is never such that in future no changes will be made and if such changes are made and new resources are added then the developer knows that he has to release those resources in Dispose function.