たとえば、のusing
代わりにメソッドを使用するFileStream.Close();
と、クラスは正しく破棄されますか?
private static string GetString()
{
using(FileStream fs = new FileStream("path", FileMode.Open))
using(StreamReader sr = new StreamReader(fs))
{
return sr.ReadToEnd();
}
}
と同等です:
private static string GetString()
{
string toReturn = "";
FileStream fs = new FileStream("path", FileMode.Open)
StreamReader sr = new StreamReader(fs)
toReturn = sr.ReadToEnd();
sr.Close();
fs.Close();
return toReturn;
}
または:
private static string GetString()
{
FileStream fs;
StreamReader sr;
try
{
string toReturn = "";
fs = new FileStream("path", FileMode.Open)
sr = new StreamReader(fs)
toReturn = sr.ReadToEnd();
sr.Close();
fs.Close();
return toReturn;
}
finally
{
if(sr != null)
sr.Close();
if(fs != null)
fs.Close();
}
}