C#4.0的dynamic用法(一)——巧用反射

在平時做框架架構設計的時候,頭疼之一的是處處得采用反射,但有了C#4.0,發現dynamic完全可以取代反射,這個功能讓我有些激動,立馬在VS2010將日誌跟蹤器框架裏的第一個反射的代碼升級到C#4.0,結果一點都不令人失望,代碼簡化了很多。
先看看用dynamic替換反射後的代碼吧: 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Reflection;
 6 using System.IO;
 7 /********************************
 8  * Updated by Lihua at 03/13/2009
 9  * 
10  * 更新功能:
11  * 1. 升級到C#4.0,加入dynamic代替反射
12  * 2. 如果Zivsoft.Log.dll不存在,日誌不輸出
13  * 3. 項目編譯不依賴於Zivsoft.Log.dll
14  ****************************************/
15 namespace Zivsoft.Data
16 {
17     /// <summary>
18     /// 只提供持久數據層框架裏的類使用
19     /// </summary>
20     internal class Logger
21     {
22         private static Assembly _assemblyFile;
23         private static dynamic _logger;
24         static Logger()
25         {
26             var strDllFile = AppDomain.CurrentDomain.BaseDirectory + "Zivsoft.Log.dll";
27             if (File.Exists(strDllFile))
28             {
29                 _assemblyFile = Assembly.LoadFile(strDllFile);
30                 try
31                 {
32                     _logger = _assemblyFile.CreateInstance("Zivsoft.Log.Logger"false, BindingFlags.CreateInstance, nullnullnullnull);
33                 }
34                 catch {
35                     _logger = null;
36                 }
37             }
38         }
39 
40         public static void LogInfo(string message, params object[] args)
41         {
42             if (null != _logger)
43             {
44                 _logger.LogInfo(message, args);
45             }
46         }
47 
48         public static void LogWarning(string message, params object[] args)
49         {
50             if (null != _logger)
51             {
52                 _logger.LogWarning(message, args);
53             }
54         }
55 
56         public static void LogError(string message, params object[] args)
57         {
58             if (null != _logger)
59             {
60                 _logger.LogError(message, args);
61             }
62         }
63 
64         public static void LogDebug(string message, params object[] args)
65         {
66             if (null != _logger)
67             {
68                 _logger.LogDebug(message, args);
69             }
70         }
71 
72         public static void LogError(Exception e)
73         {
74             LogError("{0}", e);
75         }
76     }
77 }
78 

 

以上是持久數據層調用日誌跟蹤器的入口代碼,以前採用反射,剛被我用dynamic改了過來,經調試一點問題都沒有,所以這讓我欣喜,因爲接下來的我的很多框架採用反射的機制將都可能被dynamic替換,比如《持久數據層框架》中的被反射的SQLServer, MySQL, Access等等數據庫。

不多寫了,大家仔細體會吧。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章