標籤:style blog http color 使用 io strong ar
如何通過Action重複的代碼
其實提高代碼的重用,有幾個途徑
a.繼承
b.工具方法
c.使用委託
a,b兩點都很容易理解,說一下"c"這一點,舉個DataContext事務的例子
using(var context = new DataContext()){ context .BeginTransaction(); try { context.User.GetUser(); context.User.add(new User{name="xian"});
context.User.add(new User{name="hong"}); context.Commit(); } catch { context.Rollback(); } }
以上代碼很常見吧,是不是每個使用事務地方都需要這麼寫,其實這個時候我們可以利用委託來實現
public class DbInvoker { public void Transaction(Action<DataContext> aciton) { using (var context = new DataContext()) { context.BeginTransaction(); try { aciton(context); context.Commit(); } catch { context.Rollback(); } } } }
以後用到事務的地方這樣調用就行了
DbInvoker.Transaction(context=>{ context.User.Add(new User{name="xian"}); context.User.Add(new User{name="hong"});});
是不是方便了許多.
上述主要是保持一個原則:提出變化,封裝固定操作!
其中:BeginTransaction、Commit、Rollback 為固定操作;
而context.User.GetUser();context.User.add(new User{name="xian"});
context.User.add(new User{name="hong"});
為固定操作。
aciton(context); 可以這樣理解相當於一個無傳回值,參數為Context方法。
Public void ExecutAction(Context content)
{
}