我正在使用一个C#API,它具有相当复杂的虚拟方法调用顺序,可以在类型层次结构的各个级别中重写。我希望能够记录这些方法的执行顺序,我想知道是否有办法做到这一点,而不必使用Trace写入类。鉴于这些类中的每一个都有超过2k的LOC,手动完成这将是一项非常艰巨的任务!
让我试着给出常见方法流程的快速示例:
public class Base
{
protected void Init()
{
this.BeginInitInternal();
this.OnInit();
this.AfterInitInternal();
}
protected virtual void AfterInitInternal() { }
protected virtual void OnInit() { }
protected virtual void BeginInitInternal() { }
}
public class Derived : Base
{
protected sealed override void BeginInitInternal()
{
// Logic here
this.BeginInit();
}
protected sealed override void AfterInitInternal()
{
// Logic here
this.AfterInit();
}
protected virtual void BeginInit() { }
protected virtual void AfterInit() { }
}
public class Concrete : Derived
{
protected override void BeginInit() { /* Logic here */ }
protected override void OnInit() { /* Logic here */ }
protected override void AfterInit() { /* Logic here */ }
}
Concrete
实现是由API的使用者创建的,我希望能够告诉他/她所有这些调用的顺序(理想情况下也是上下文,但这不在范围之内)问题。
我不一定需要一个UML序列图,但这是我发现的最接近的模拟物。
理想情况下,我希望告诉该工具在Base.Init()
上查看Derived
的实现并发出如下内容:
Derived.BeginInit()
Base.OnInit()
Derived.AfterInit()
我已经尝试过VS序列图生成器,但我似乎无法告诉它使用Concrete
但是从Base.Init()
开始。我也尝试过使用VS代码映射,但它会解决解决方案的复杂性,并且通常会出错。最后,我尝试使用NDepend,它接近 - 它可以告诉我所有的调用,但不是它们的顺序。
还有什么我可以尝试的,或者我是否应该开始在任何地方粘贴Trace.WriteLines
?
答案 0 :(得分:1)
喔。这是使用Roslyn的好例子。
如果您想从源代码中提取自定义信息,这取决于源代码,而不会让源代码适应您的阅读器;我想说这是使用Roslyn的一个很好的例子。
答案 1 :(得分:0)
您可以考虑拦截对每种方法的调用,并且可以开箱即用,创建文档等。
你可以在这里看到我们如何拦截方法调用。
http://dotnetdlr.com/2011/05/06/intercept-calls-to-objects-in-c/