在IDisposable的问题 [英] Question on IDisposable

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

问题描述

我的问题是,为什么我需要IDisposable的?我有一个消耗一些资源类 被释放这一需求。我有两个选择

如果没有了IDisposable

 类SomeUtilityClass
{
 公共停止()
 {
   //免费资源
 }
}
 

使用了IDisposable

 类SomeUtilityClass,IDisposable的
    {
     公共无效的Dispose()
     {
       //免费资源
     }
    }
 

那么,为什么我需要IDisposable的吗?它不matther如何命名的功能。

 类节目
{

 公共主(..)
 {
   SomeUtilityClass _class =新SomeUtilityClass();

   //清理,当我们已经做了

  _class.Stop();

   // 要么
  _class.Dispose();

 }
}
 

解决方案

由于IDisposable接口支持C#中,你可以用爽使用语法:

 使用(IDisposable的someDisposable =新...)
{
    //你的code与someDisposable
}
 

这实际上是由编译器转换为这样的:

  IDisposable的someDisposable =新...
IDisposable的someDisposable2 = someDisposable;
尝试
{
    //你的code与someDisposable
}
最后
{
    如果(someDisposable2!= NULL)
    {
        someDisposable2.Dispose();
    }
}
 

因此​​,如果任何异常里面碰巧使用阻止你的对象将被无论如何处置。

My question is why do I need IDisposable? I have a class that consumes some resources that need to be freed. I have two options

Without IDisposable

class SomeUtilityClass
{
 public Stop()
 {
   // free resources
 }
}

With IDisposable

    class SomeUtilityClass, IDisposable
    {
     public void Dispose()
     {
       // free resources
     }
    }

So why do I need IDisposable here? It does not matther how to name the function.

class Program
{

 public Main(..)
 {
   SomeUtilityClass _class = new SomeUtilityClass();

   // clean up when we've done

  _class.Stop();

   // OR
  _class.Dispose();

 }
}

解决方案

Because IDisposable is supported by C# and you can use cool using syntax:

using (IDisposable someDisposable = new ...)
{
    // your code with someDisposable 
}

This is actually transformed by compiler to something like:

IDisposable someDisposable = new ...
IDisposable someDisposable2 = someDisposable ;
try
{
    // your code with someDisposable 
}
finally
{
    if (someDisposable2 != null)
    {
        someDisposable2.Dispose();
    }
}

So if any exception happens inside using block your object would be disposed anyway.

这篇关于在IDisposable的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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