如何让PostSharp在Visual Studio生成窗口输出切面验证消息?
PostSharp编译期切面输出到VS生成窗口的解决方案
PostSharp的编译期代码运行在独立的编译进程中,直接使用Console/Debug/Trace类的输出方法无法关联到Visual Studio的生成窗口,必须使用PostSharp自带的**Message.Write**方法,它专门用于在编译阶段向宿主(VS/MSBuild)输出信息。
修改后的代码示例
[PSerializable] public class LogEventAttribute : EventInterceptionAspect { public override void CompileTimeInitialize(EventInfo targetEvent, AspectInfo aspectInfo) { // 使用PostSharp的Message类输出到生成窗口 Message.Write(Severity.Info, "LogEventAspect", ">>>>> EVENT: {0} CLASS: {1}", targetEvent.Name, targetEvent.DeclaringType?.FullName); base.CompileTimeInitialize(targetEvent, aspectInfo); } }
额外说明
- 通过
Severity参数可控制输出级别:Info/Warning/Error,对应VS生成窗口的不同颜色提示 - 输出内容会直接显示在Visual Studio的「生成」标签页中,无需额外配置
- 若需关联具体代码位置,可在
Message.Write中添加Location参数,将输出定位到目标事件的定义处
内容的提问来源于stack exchange,提问作者Dan Sorak
相关产品推荐
相关产品推荐

