为什么代码分析会告诉我“不要多次放置对象”?这里: [英] Why does Code Analysis tell me, "Do not dispose objects multiple times" here:

查看:73
本文介绍了为什么代码分析会告诉我“不要多次放置对象”?这里:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此代码上:

public static string Base64FromFileName(string fileName)
{
    try
    {
        FileInfo fInfo = new FileInfo(fileName);
        long numBytes = fInfo.Length;
        FileStream fStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fStream);
        byte[] bdata = br.ReadBytes((int)numBytes);
        br.Close();
        fStream.Close();
        return Convert.ToBase64String(bdata);
    }
    catch(Exception e)
    {
        throw e;
    }
}

...我得到了,由Visual Studio的代码提供分析工具,警告 请勿多次处置对象...为避免生成System.ObjectDisposedException,您不应在对象上调用Dispose多次 在 fStream.Close( );线。

...I get, courtesy of Visual Studio's Code Analysis tool, the warning, "Do not dispose objects multiple times...To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object" on the "fStream.Close();" line.

为什么? fStream是否放置在上面关闭BinaryReader的行中?

Why? Is fStream disposed in the line above, where the BinaryReader is closed?

无论如何,我最好不要重构它吗?

Wouldn't I be better off refactoring it like this anyway:

. . .
using (FileStream fStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))   
{
    using (BinaryReader br = new BinaryReader(fStream)) 
    {
        byte[] bdata = br.ReadBytes((int)numBytes);
    } //br.Close();
} //fStream.Close();
. . .

推荐答案

BinaryReader.Close 也会关闭基础流,因此确实会导致该流被丢弃两次。但这不是一个真正的问题,处理两次不会造成伤害。

BinaryReader.Close also closes the underlying stream, so this would indeed cause the stream to be disposed of twice. But that's not a real problem, disposing twice doesn't hurt.

您可以写得更好,因为

using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
using (var br = new BinaryReader(fs, new UTF8Encoding(), true))
{
    return Convert.ToBase64String(br.ReadBytes((int)numBytes));
}

这是防弹版本:


  • 任何成功构造的东西都保证会被丢弃

  • 您不会将流丢弃两次,因为布尔值<$ c BinaryReader 构造函数上的$ c> leaveOpen 参数可确保处置(关闭)它也不会关闭流

  • Anything that is successfully constructed is guaranteed to be disposed
  • You won't dispose of the stream twice because the boolean leaveOpen argument on the BinaryReader constructor ensures that disposing (closing) it won't also close the stream

这篇关于为什么代码分析会告诉我“不要多次放置对象”?这里:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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