如果您使用该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();
}
}