1.C#中通过委托Action消除重复代码

阅读目录

  一:重复的代码
  二:使用委托消除重复代码

    一:重复的代码
   
我们在写一些方法的时候,会在里面可能出现异常的地方使用try catch语句,这样每个方法都会有try catch语句,这样就有了坏味道,如下所示,在GetName和GetAge里面都有try catch语句,这样就有了重复代码

 1 static void Main(string[] args)
 2         {
 3             GetName();
 4             GetAge();
 5             Console.ReadLine();
 6         }
 7 
 8         private static void GetName()
 9         {
10             try
11             {
12                 Console.WriteLine("My name is david");
13             }
14             catch (Exception ex)
15             {
16 
17             }
18           
19         }
20 
21         private static void GetAge()
22         {
23             try
24             {
25                 Console.WriteLine("I 30 old years");
26             }
27             catch (Exception ex)
28             {
29 
30             }
31         }

  二:使用委托Action消除重复代码
     
如下所示,try catch 语句只有一次了,这样就消除了每个方法的try catch语句

 1         static void Main(string[] args)
 2         {
 3             GetName();
 4             GetAge();
 5             Console.ReadLine();
 6         }
 7 
 8         private static void GetName()
 9         {
10             TryExecute(() =>
11             {
12                 Console.WriteLine("My name is david");
13             },
14           "GetName");
15         }
16 
17         private static void GetAge()
18         {
19             TryExecute(() => {
20                 Console.WriteLine("I 30 old years");
21             },"GetAge");
22         }
23 
24         private static void TryExecute(Action action, string methodName)
25         {
26             try
27             {
28                 action();
29             }
30             catch (Exception ex)
31             {
32                 Console.WriteLine("MethodName:" + methodName + " Error:" + ex.Message);
33             }
34         }

 

 

 

posted @ 2016-03-10 09:29  David.Meng  阅读(1290)  评论(0编辑  收藏  举报