在 .NET 中是否有任何模式或实践以非侵入性方式将 debug/log 代码引入现有算法?

Is there any pattern or practice to introduce debug/log code to an already existing algorithm in a non-intrusive way in .NET?

假设我有一个已经存在的大型算法,可以进行一些计算并 returns 结果:

public int JustSomeHeavyCalculations() {
    var storeSthing = PrivateFunction1("param");
    if (Somecondition) {
        var variable = member.DoSomething() + member2.DoSomething2()
    }

    CallSomePrivateFunction();
    return storeSthing * someRandNumber;
}

现在我有一个新要求,说我必须登录一个文件并在控制台上打印 "variable" 的值,并且 PrivateFunction1 是一项昂贵的操作,应该以调用的方式进行缓存它再次使用相同的参数立即 returns 缓存值。

我可以轻松一点,修改函数并添加所有这些语句,但这不仅对我来说违反了开闭原则,而且我觉得它会破坏流程算法。

处理这种情况的最佳方法是什么?

在我看来,这些是面向方面编程旨在解决的 classic 类型的横切关注点。横切关注点跨越代码中的层和层,但理想情况下,您希望以非侵入式方式在一个地方实施。面向方面的编程允许在编译时或 运行 时从 class 继承权外部将行为应用于 classes。

Microsoft Application Architecture guide has a good section on what cross cutting concerns are as well as some ideas on how to implement them. A google for .NET Aspect Oriented Programming will find the various libraries that implement Aspects on .NET or start on the aosd.net 网站。