相关疑难解决方法(0)

方法返回一个IDisposable - 我应该处理结果,即使它没有分配给任何东西?

这似乎是一个相当简单的问题,但在搜索之后我找不到这个特殊的用例.

假设我有一个简单的方法,比如确定某个进程是否打开了一个文件.我可以这样做(不是100%正确,但相当不错):

public bool IsOpen(string fileName)
{
  try
  {
    File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None);
  }
  catch
  {
    // if an exception is thrown, the file must be opened by some other process
    return true;
  } 
}
Run Code Online (Sandbox Code Playgroud)

(显然,这不是确定这一点的最佳或甚至是正确的方法 - File.Open会抛出许多不同的异常,所有异常都具有不同的含义,但它适用于此示例)

现在File.Open调用返回a FileStream,并FileStream实现IDisposable.通常我们想要FileStream在使用块中包装任何实例化的用法,以确保它们被正确处理掉.但是在我们实际上没有将返回值分配给任何东西的情况下会发生什么?是否仍然需要处理FileStream,如下:

try
{
  using (File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None));
  { /* nop */ }
}
catch 
{
  return true;
}
Run Code Online (Sandbox Code Playgroud)

我应该创建一个FileStream实例并处理它吗?

try
{
  using (FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None)); …
Run Code Online (Sandbox Code Playgroud)

c# idisposable

5
推荐指数
2
解决办法
1903
查看次数

如果我不调用dispose()会发生什么?

    public void screenShot(string path)
    {
        var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
                                        Screen.PrimaryScreen.Bounds.Height,
                                        PixelFormat.Format32bppArgb);

        var gfxScreenshot = Graphics.FromImage(bmpScreenshot);
        gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                                    Screen.PrimaryScreen.Bounds.Y,
                                    0,
                                    0,
                                    Screen.PrimaryScreen.Bounds.Size,
                                    CopyPixelOperation.SourceCopy);

        bmpScreenshot.Save(path, ImageFormat.Png);
    }
Run Code Online (Sandbox Code Playgroud)

我正在使用此代码捕获我的计算机屏幕.

但今天我发现有一个名为Bitmap.Dispose()的方法.

什么时候调用Dispose()有什么区别?代码运行至关重要吗?

c# dispose bitmap

5
推荐指数
2
解决办法
4400
查看次数

标签 统计

c# ×2

bitmap ×1

dispose ×1

idisposable ×1