How do you use Func<> and Action<> when designing applications?

后端 未结 9 973
情书的邮戳
情书的邮戳 2020-12-22 16:27

All the examples I can find about Func<> and Action<> are simple as in the one below where you see how they technically work but I would like

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-22 17:12

    I use an Action to nicely encapsulate executing database operations in a transaction:

    public class InTran
    {
        protected virtual string ConnString
        {
            get { return ConfigurationManager.AppSettings["YourDBConnString"]; }
        }
    
        public void Exec(Action a)
        {
            using (var dbTran = new DBTransaction(ConnString))
            {
                try
                {
                    a(dbTran);
                    dbTran.Commit();
                }
                catch
                {
                    dbTran.Rollback();
                    throw;
                }
            }
        }
    }
    

    Now to execute in a transaction I simply do

    new InTran().Exec(tran => ...some SQL operation...);
    

    The InTran class can reside in a common library, reducing duplication and provides a singe location for future functionality adjustments.

提交回复
热议问题