从方法返回一次性对象 [英] Returning a Disposable Object from a Method

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

问题描述

在MSDN网站上的
MSDN建议

On the MSDN site in the topic about code analysis warning CA2000, a general pattern is recommended for a method which returns a disposable object. Can anyone explain why this pattern needs the temporary variable and why it uses a ''finally'' clause rather than a ''catch'' clause for code which is only relevant when an exception occurs? In other words, is there any reason why the MSDN recommmendation would be preferable to the second code sample below?

MSDN Recommendation

public SerialPort OpenPort2(string portName)
{
   SerialPort tempPort = null;
   SerialPort port = null;
   try
   {
      tempPort = new SerialPort(portName);
      tempPort.Open();
      SomeMethod();
      //Add any other methods above this line
      port = tempPort;
      tempPort = null;

   }
   finally
   {
      if (tempPort != null)
      {
         tempPort.Close();
      }
   }
   return port;
}


为什么不这么简单?


Why Not This Simplification?

public SerialPort OpenPort2(string portName)
{
    SerialPort port = null;
    try
    {
        port = new SerialPort(portName);
        port.Open();
        SomeMethod();
        //Add any other methods above this line
    }
    catch
    {
        if (port != null)
        {
            port.Close();
        }
        throw;
    }
    return port;
}

推荐答案

原因是catch 块仅在抛出exception 时被执行,而finally 块在两个中都被执行在没有例外的情况下正常执行的情况,以及万一发生例外的情况.

因此,在第二个示例中,port.Close仅在发生异常时执行,并在正常执行中保持打开状态.根据用于实现IDisposable 接口的对象的MSDN文档,在finally 块中将调用Dispose 方法.
一次性模式通过IDisposable 接口实现,以确保正确释放对象持有的资源.

try finally块由using block隐式实现,并且将using 块与实现IDisposable 接口的对象一起使用很方便,如此处
The reason is that the catch block gets executed only if an exception is thrown, whereas the finally block gets executed both in case of normal execution without an exception and in case an exception occurs.

So, in the second example the port.Close gets executed only when an exception occurs and remains open in the normal execution. As per MSDN documentation for an object implementing the IDisposable interface the Dispose method is to be called in the finally block.

The disposable pattern is implemented with IDisposable interface to ensure that the resources held by an object are released properly.

The try finally block is implicitly implemented by the using block and it is convenient to use using block with an object implementing IDisposable interface as explained here http://msdn.microsoft.com/en-us/library/yh598w02.aspx[^]


我想这取决于一次性物品.为简化起见,您尝试打开一个端口,允许发生任何错误,尝试关闭该端口,然后返回相同的端口.因此,如果端口对象包含有关已完成操作的任何状态信息,则您将获得尝试初始化所造成的任何混乱,而不是像MSDN示例中那样产生干净的空副本.
I''d guess it depends on the disposable object. In your simplification, you attempt to open a port, allow any error to occur, attempt to close the port, and then return that same port. So if the port object holds any state information about what''s been done to it, you''ve got whatever mess was created by your attempted initialization instead of a clean, null copy, as in the MSDN example.


这篇关于从方法返回一次性对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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