【问题标题】:How can I get a method's parameters in plain text in C#?如何在 C# 中以纯文本形式获取方法的参数?
【发布时间】:2022-01-07 16:45:53
【问题描述】:

我们使用“自己的”断言方法,允许传递消息但不强制传递消息。 我们的大多数代码库都使用“无消息”的...当您有多个断言并且代码在错误报告和错误修复之间发生变化时,这是有问题的...

我想在断言消息中以纯文本形式打印调用者行。比如:

int toto = 1;
SomObject obj = null;

Assert(toto == 0);
Assert(obj);
Assert(toto == 0, "some useful info");

预期输出:

Assertion failed. Parameter='toto == 0'
Assertion failed. Parameter='obj'
Assertion failed. 'some useful info'

我们发现这个帖子在谈论 Cecil Mono.Cecil - simple example how to get method body ...

这可能是一种方法,但意味着我们必须根据 ILCode 重建线路。 有没有办法以其他方式获取“纯文本代码”?

[编辑] 我们在 C# 8 上运行。

【问题讨论】:

    标签: c#


    【解决方案1】:

    您可以尝试CallerArgumentExpressionAttribute (https://docs.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callerargumentexpressionattribute?view=net-6.0) 来获取实际的断言表达式/条件并将其显示为消息。

    public static void Assert(bool condition, 
        [CallerArgumentExpression("condition")] string message = null)
    {
        //code here
    }
    

    用法

    // message argument in Assert will be "result==true" (as string)
    Assert(result==true);
    
    // message argument in Assert will be "Custom message"
    Assert(result==true, "Custom message");
    

    【讨论】:

    • 正如链接所说,此属性从 C#10 开始可用
    • arf...我一直在微笑,直到我读到我们的评论 ^^ 当我们在“Unity's C#”上运行时,它现在遥不可及...很高兴知道有一个“简单”在某个地方做这件事的方法。感谢您的回答和评论!
    • @ThorTillas,我不熟悉 Unity 的限制,但对于普通的 C# CallerArgumentExpressionAttribute 可以向后移植到旧版本 - 有关详细信息,请参阅此处stackoverflow.com/questions/70034586/…
    猜你喜欢
    • 2016-03-03
    • 2019-04-26
    • 2015-12-08
    • 1970-01-01
    • 2021-03-21
    • 2012-08-13
    • 2020-09-09
    • 2021-06-11
    • 1970-01-01
    相关资源
    最近更新 更多