何时处置?

由网友(〈 羙妙旳·夢)分享简介:我弄不清这一切谈IDispose和使用声明。我不知道是否有人能告诉我,如果我需要使用一个使用的声明,或在下面的测试示例某种实施IDispose的...... 谢谢... 公共类的Main(){MyFile的MYFILE =新MyFile的(C:\子目录\ subdir2 \ TESTFILE.TXT);Console...

我弄不清这一切谈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

江苏拟立法整治 医闹 医疗索赔超2万不得私了

现在,如果你改变了你的类的开启的文件,并保持的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:subdirsubdir2testFile.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.

阅读全文

相关推荐

最新文章