鉴于此代码:
/// <summary>
/// Add to view count of this article
/// </summary>
public static void IncrementViewCount(int articleID)
{
using (var db = new MainContext())
{
var q = (from c in db.tblArticles where c.ID == articleID select c).SingleOrDefault();
if (q != null)
{
q.Views ++;
db.SubmitChanges();
if (q.Views == 500)
{
// Call function
}
}
}
}
用以下方式写它更好吗:
/// <summary>
/// Add to view count of this article
/// </summary>
public static void IncrementViewCount(int articleID)
{
var newViews = 0;
using (var db = new MainContext())
{
var q = (from c in db.tblArticles where c.ID == articleID select c).SingleOrDefault();
if (q != null)
{
newViews = q.Views + 1;
q.Views = newViews;
db.SubmitChanges();
}
}
if (newViews == 500)
{
// Call function
}
}
请注意,在示例 #2 中,using 块在较早的时间点关闭。