为什么我应该使用 IDisposable 而不是在 c# 中使用? [英] Why should I use IDisposable instead of using in c#?

查看:29
本文介绍了为什么我应该使用 IDisposable 而不是在 c# 中使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天想对一个文件进行操作所以想出了这个代码

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. 
            }
        }
    }

但是在代码审查中,我被要求实现 IDisposable 接口和 Finalizer 方法

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?

推荐答案

No One"给出的答案是正确的,using 块只能用于实现 的类IDisposable 接口和对它的解释是完美的.您这边的问题是为什么我需要在 Test 类上添加 IDisposable,但是在代码审查中,我被要求在 Test 类上实现 IDisposable 接口和 Finalizer 方法."
答案很简单
1) 根据许多开发人员遵循的编码标准,在使用某些资源的类上实现 IDisposable 总是好的,一旦该对象的范围超过该类中的 Dispose 方法将确保所有资源都已释放.
2)已编写的类永远不会在将来不会进行任何更改,如果进行了此类更改并添加了新资源,则开发人员知道他必须在 Dispose 函数中释放这些资源.

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.

这篇关于为什么我应该使用 IDisposable 而不是在 c# 中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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