C# 通過Action委託提高代碼的重用

來源:互聯網
上載者:User

標籤: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)
{

}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.