问题
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...
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;
}
}
回答1:
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.
回答2:
No, in the code provided I don't see any resource used that have to be disposed. So the answer is no, do not use in this code it.
回答3:
In your example there is nothing to dispose, so you have no need to do that.
If you want to read/write in file you can use Streamreader/Streamwriter for that and in that way you will need to dispose that objects after using them.
using(StreamReader sreader=new StreamReader())
{
//your code
}
So in this case using statement will help you to don't think about manually disposing/closing your object/
回答4:
In your code there is no need for any Dispose / using - for a definitive guide on IDisposable see here.
来源:https://stackoverflow.com/questions/9777302/when-to-dispose