1、安装NuGet工具。
打开VS,在菜单“工具”->"扩展管理器",选择联机库,选择安装NuGet程序包管理器
2、安装PostSharp3.0.0版本。下载地址:http://www.postsharp.net/download
3、打开VS,创建控制台应用程序。
右击项目,可以看到PostSharp选项。给这个项目添加PostSharp。完成这些动作之后,这个项目就可以使用PostSharp了。
代码如下:
class Program
{
static void Main(string[] args)
{
Describe();
Console.Read();
}
[Exception]
public static void Describe()
{
Console.WriteLine(String.Format("hello PostSharp"));
}
}
}
[Serializable]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class ExceptionAttribute : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionArgs eventArgs)
{
Util.Writelog("开始执行");
}
public override void OnExit(MethodExecutionArgs eventArgs)
{
Util.Writelog("成功完成");
}
}
public class Util
{
private const String _errLogFilePath = @"log.txt";
public static void Writelog(String message)
{
StreamWriter sw = new StreamWriter(_errLogFilePath, true);
String logContent = String.Format("[{0}]{1}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"), message);
sw.WriteLine(logContent);
sw.Flush();
sw.Close();
}
}