在使用语句中从内部返回一个方法值,获取DataContext似乎总是可以很好地工作,就像这样:
public static Transaction GetMostRecentTransaction(int singleId)
{
using (var db = new DataClasses1DataContext())
{
var transaction = (from t in db.Transactions
orderby t.WhenCreated descending
where t.Id == singleId
select t).SingleOrDefault();
return transaction;
}
}
但我总觉得在跳出using括号之前,应该先完成某些操作,例如在using语句之前定义事务,然后在括号内获取其值,在括号之后返回。
将变量的定义和返回放在using括号外面是否是更好的做法,或者能以某种方式节省资源?