哪種方法更有效(時間,內存,資源釋放,異常情況)?方法範圍中的資源釋放與使用.NET中的塊範圍的關係
public static string getFileData(string filePath)
{
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
using (StreamReader r = new StreamReader(fs))
{
return r.ReadToEnd();
}
}
}
OR
public static string getFileData(string filePath)
{
return (new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read)).ReadToEnd());
}
很明顯,第二個簡單地*不釋放資源......它不是關於效率,而是關於正確性。雖然我只是使用File.ReadAllText ... –
我個人會使用using語句來顯式地顯示資源在其他人閱讀代碼時被管理和處置,但是發生了什麼更清晰。 –