如果您使用using
方法而不是可以說,該類將正確配置嗎?從方法返回正確配置對象?
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();
}
}
通過使用搜索引擎找到C#''using'的文檔有多困難? –
http://stackoverflow.com/questions/667111/some-advanced-questions-on-the-using-statement –