何时处置? [英] When to Dispose?

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

问题描述

我弄不清这一切谈IDispose和使用声明。我不知道是否有人能告诉我,如果我需要使用一个使用的声明,或在下面的测试示例某种实施IDispose的......

谢谢...

 公共类的Main()
{
    MyFile的MYFILE =新MyFile的(C:\子目录\ subdir2 \ TESTFILE.TXT);
    Console.Writeline(文件名:+ myFile.FileName()+文件大小:+ myFile.FileSize());
}

公共类为MyFile
{
    私人的FileInfo _fInfo;

    公共MyFile的(字符串fullFilePath)
    {
        _fInfo =新的FileInfo(fullFilePath);
    }

    公共字符串的文件名()
    {
        返回_fInfo.Name;
    }

    众长文件大小()
    {
        返回_fInfo.Length;
    }

}
 

解决方案

没有,你的例子不使用的需要处置的任何资源(它不碰任何东西,它实现的IDisposable ,或有任何直接处理非托管资源),所以你并不需要实现的IDisposable

现在,如果你改变了你的类的开启的文件,并保持的FileStream 字段指的是打开的文件句柄,的这将是有意义的实施的IDisposable 关闭这个流。

I'm getting confused about all this talk about IDispose and "using" Statements. I wonder if someone can tell me if I need to use either a "using" Statement or some sort of implementation of IDispose in the following test example...

Thanks...

public class Main()
{
    MyFile myFile = new MyFile("c:\subdir\subdir2\testFile.txt");
    Console.Writeline("File Name: " + myFile.FileName() + "File Size: " + myFile.FileSize());
}

public class MyFile
{
    private FileInfo _fInfo;

    public MyFile(string fullFilePath)
    {
        _fInfo = new FileInfo(fullFilePath);
    }

    public string FileName()
    {
        return _fInfo.Name;
    }

    public long FileSize()
    {
        return _fInfo.Length;
    }

}

解决方案

No, your example doesn't use any resources which need disposing (it doesn't touch anything which implements IDisposable, or have any direct handles to unmanaged resources) so you don't need to implement IDisposable.

Now if you changed your class to open the file, and maintain a FileStream field referring to the open file handle, then it would make sense to implement IDisposable to close the stream.

这篇关于何时处置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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