2.轉型使用as來轉型,用as轉型時若轉型失敗會得到null不會發生例外,用明確轉型,還要檢查是否為null以及捕捉例外,便會降低程式碼的效能
3.請盡量使用LINQ查詢語法而不是使用迴圈
1.使用 using 或 try/finally 清理資源
為了確保資源一定會被釋放我們可以改成以下,將釋放的程式碼寫在finally區段裡面。
public string ReaderLine(string FileName) { if (!File.Exists(FileName)) return null; Stream stream = null; StreamReader reader = null; string line=""; string result=""; try { stream = File.Open(FileName, FileMode.Open); reader = new StreamReader(stream); while ((line = reader.ReadLine()) != null) { result += line + Environment.NewLine; } string a = "999"; byte b = byte.Parse(a); return result; } catch (Exception ex) { Console.WriteLine(ex.Message); return null; } finally { reader.Close(); stream.Close(); } }
除了資源的釋放,我也常用在執行緒的釋放Monitor.Enter(_thisLock); try { //TODO } finally { Monitor.Exit(_thisLock); }
2.轉型使用as來轉型,用as轉型時若轉型失敗會得到null不會發生例外,用明確轉型,還要檢查是否為null以及捕捉例外,便會降低程式碼的效能
object company = new Company(); Family family = company as Family; if (family != null) { //TODO } else { //TODO }
3.查詢盡量使用LINQ查詢而不是使用迴圈
沒有留言:
張貼留言