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不存在,日志不输出www.elivn.com
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等等数据库。

不多写了,大家仔细体会吧。

posted on 2011-04-25 13:29  seoxs  阅读(495)  评论(0编辑  收藏  举报

导航