gpt4 book ai didi

c# - 让 PostSharp 帮助记录 IF 语句

转载 作者:太空宇宙 更新时间:2023-11-03 10:22:25 25 4
gpt4 key购买 nike

我正在寻找的行为类似于以下内容:

[IfElseLogging]
public void Foo(string bar)
{
if (bar == "somedumbstringbecausethisishorriblewayofdoingthings")
{
// here the aspect would log that the if statement above was true,
// and thus took this path
}
else
{
// here the aspect would log that the if statement above was false,
// and thus took this path
}
}

如果有一种方法可以劫持 if 功能,我就可以用 Postsharp 使用的日志记录来装饰它并擦掉我手上的灰尘。我添加到问题中的另一个原因是我不确定我是否清楚我在问什么。

这是一个非常初级的开发人员完成的项目。我的任务不仅是重构,而且记录代码在流程图级别上究竟做了什么。考虑到代码的性质、缺乏描述、糟糕的技术和实践、项目的性质等……以下是我正在努力解决的问题:

  • 我不能简单地在本地调试和单步调试代码
  • 我无法安全地创建单元测试和重构
  • 我无法理解这段代码的作用!
  • 我没有原始需求文档来了解该功能的目标是什么

所以我希望使用 Postsharp 基本上为我提供我的代码路径和单元测试标准,因为我不知道还有什么方法可以得到它。

换个思路,是否可以有一个切面在发现 if 语句时触发事件?

最佳答案

使用 PostSharp 进行面向方面的编程将允许您创建拦截器,这些拦截器可以在定义明确的点(例如方法调用和属性访问)挂接到您的代码中。这是通过重写从您的源代码生成的 IL 来完成的。

在您的情况下,您正在寻找特定的 if 语句,但它们在生成的 IL 中不容易识别。以下是为您的示例方法生成的内容:

          nop          ldarg.1               ldstr       "somedumbstringbecausethisishorriblewayofdoingthings"          call        System.String.op_Equality          stloc.0          ldloc.0          brfalse.s   NotEqual          nop**True branch**          br.s        ReturnNotEqual: nop**False branch**Return:   ret

However, this is the non-optimized version. The optimizing compiler generates this code:

          ldarg.1          ldstr       "somedumbstringbecausethisishorriblewayofdoingthings"          call        System.String.op_Equality          brfalse.s   NotEqual**True branch**          retNotEqual:**False branch**           ret

So if you want to do IL rewriting you could conceivably intercept method calls, look for an IL signature that looks something like ldstr, "...", call System.String.op_Equality, brfalse.s and then rewrite the IL to modify the code. However, this approach is extremely fragile. Small differences in the source code may generate IL with a different signature and only the compiler writers will really know the entire range of IL signatures you have too look for. If the conditional statement involves several terms combined with logical operators then it can become very complicated to determine where to insert your instrumentation code. And then there are false positives. Personally, I do not believe this is a viable strategy for instrumenting your code.

However, you have another option. You can compile the source code using Roslyn and use Roslyn rewriters to modify the original source tree. This is AOP at the source level as opposed to PostSharp that offers AOP at the IL level.

To rewrite a syntax tree you need to derive a class from CSharpSyntaxRewriter. This rewriter will modify if statements so the VisitIfStatement method is overridden:

class IfStatementRewriter : CSharpSyntaxRewriter {

public override SyntaxNode VisitIfStatement(IfStatementSyntax ifStatement) {
var containsMagicString = ifStatement
.Condition
.DescendantNodes()
.Any(
syntaxNode => syntaxNode.ToString() == @"""somedumbstringbecausethisishorriblewayofdoingthings"""
);
if (!containsMagicString)
// Do not modify if statement.
return ifStatement;
// Only look at the "true" part and assume it is a block (has curly braces).
var block = ifStatement.Statement as BlockSyntax;
if (block == null)
// Do not modify if statement.
return ifStatement;
// Insert instrumentation code at start of block.
var instrumentationStatements = CreateInstrumentationStatements("True branch");
var modifiedStatements = block.Statements.InsertRange(0, instrumentationStatements);
var modifiedBlock = block.WithStatements(modifiedStatements);
return ifStatement.WithStatement(modifiedBlock);
}

}

要插入检测代码 System.Console.WriteLine("True branch"); 使用了以下相当复杂的方法:

IEnumerable<StatementSyntax> CreateInstrumentationStatements(String text) {
return SyntaxFactory.SingletonList<StatementSyntax>(
SyntaxFactory.ExpressionStatement(
SyntaxFactory.InvocationExpression(
SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.IdentifierName("System"),
SyntaxFactory.IdentifierName("Console")
)
.WithOperatorToken(SyntaxFactory.Token(SyntaxKind.DotToken)),
SyntaxFactory.IdentifierName("WriteLine")
)
.WithOperatorToken(SyntaxFactory.Token(SyntaxKind.DotToken))
)
.WithArgumentList(
SyntaxFactory.ArgumentList(
SyntaxFactory.SeparatedList(
new[] {
SyntaxFactory.Argument(
SyntaxFactory.LiteralExpression(
SyntaxKind.StringLiteralExpression,
SyntaxFactory.Literal(text)
)
)
}
)
)
)
)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
);
}

您现在可以修改语法树:

var root = (CompilationUnitSyntax) syntaxTree.GetRoot();
var rewriter = new IfStatementRewriter();
var rewrittenRoot = rewriter.Visit(root);

您将需要显着扩展代码以更好地过滤 if 语句并处理可以编写 if 语句的所有不同方式,但与 IL 重写此代码相比应该会给你更高的成功机会。

关于c# - 让 PostSharp 帮助记录 IF 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32916399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com