|  | 
 
| 本帖最后由 qq576733600 于 2013-8-13 10:17 编辑 
 在写程序的时候,很多方法都加了。日志信息。比如打印方法开始,方法结束,错误信息。等等。由于辅助性功能的代码几乎是完全相同的,这样就会令同样的代码在各个函数中出现,引入了大量冗余代码。最后找到了AOP解决方案,分享出来。供大家参考。
 
 实现步骤。
 一、下载安装 PostSharp-1.5.6.629-Release-x86.msi 或者 PostSharp-1.5.7.1081-Release-x64.msi 具体根据自己电脑来。安装的时候记得先退出自己的 Microsoft Visual Studio
 下载地址: http://www.postsharp.net/downloads/postsharp-1.5/sp-1
 
 二、在项目中添加引用
 
 添加引用   
 
 三、事例,直接贴代码了。
 [code=csharp][Serializable] //必须加入这个
 [AttributeUsage(AttributeTargets.Method,AllowMultiple=true,Inherited=true)] //设置类的访问访问
 public sealed class LoggingAttribute:OnMethodBoundaryAspect
 {
 
 public string BusinessName { get; set; }
 
 
 /// <summary>
 /// 方法进入时执行
 /// </summary>
 /// <param name="eventArgs"></param>
 public override void OnEntry(MethodExecutionEventArgs eventArgs)
 {
 
 Console.WriteLine("---------------方法:" + eventArgs.Method.Name+"开始--------------");
 }
 
 /// <summary>
 /// 方法退出时执行
 /// </summary>
 /// <param name="eventArgs"></param>
 public override void OnExit(MethodExecutionEventArgs eventArgs)
 {
 Console.WriteLine("---------------方法:" + eventArgs.Method.Name + "结束--------------");
 }
 
 
 /// <summary>
 /// 错误的时候执行
 /// </summary>
 /// <param name="eventArgs"></param>
 public override void OnException(MethodExecutionEventArgs eventArgs)
 {
 base.OnException(eventArgs);
 }
 
 //还有别的方法自己研究
 
 }[/code]
 
 注意点:类必须序列化 需要加 [Serializable]    类要配置 Attribute  设置的他的调用方式
 
 
 四、调用,非常简单。 在需要调用的 方法前面加入方法的 Attribute   就行了  下面是代码
 [code=csharp]    /// <summary>
 /// 调用事例1
 /// </summary>
 [Logging()]
 void debugInfo() {
 
 for (int i = 0; i < 3;i++ )
 {
 
 Console.WriteLine("i="+i);
 }
 }
 
 
 /// <summary>
 /// 调用事例2 ,可以给属性赋值
 /// </summary>
 [Logging(BusinessName="aaa")]
 void debugError() {
 for (int i = 0; i < 3; i++)
 {
 
 Console.WriteLine("i=" + i);
 }
 
 }[/code]
 
 五、测试结果
 
 测试结果   
 
 
 
 
 
 
 | 
 |