C# - Assert() 方法有什么作用? 还有用吗?

发布于 2024-07-05 20:57:32 字数 84 浏览 6 评论 0原文

我正在使用断点进行调试,并且我意识到断言调用? 我以为这只是用于单元测试。 它除了断点之外还有什么作用? 既然可以断点,为什么还要用Assert呢?

I am debugging with breakpoints and I realize the assert call? I thought it was only for unit tests. What does it do more than breakpoint? Since I can breakpoint, why should I use Assert?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

自由如风 2024-07-12 20:57:32

在调试编译中,断言接受布尔条件作为参数,如果条件为 false,则显示错误对话框。 如果条件为真,程序将继续执行,不会出现任何中断。

如果在 Release 中编译,所有 Debug.Assert 将自动省略。

In a debug compilation, Assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.

If you compile in Release, all Debug.Assert's are automatically left out.

乖乖兔^ω^ 2024-07-12 20:57:32

来自代码完成

8 防御性编程

8.2 断言

断言是开发过程中使用的代码——通常是例程
或宏——允许程序在运行时检查自身。 当一个
断言为真,这意味着一切都按预期运行。
当它为 false 时,意味着它检测到了意外错误
代码。 例如,如果系统假设客户信息
文件永远不会超过 50,000 条记录,程序可能
包含记录数小于或等于的断言
至 50,000。 只要记录条数小于或等于
5万,断言就会沉默。 如果遇到超过
50,000条记录,然而,它会大声“断言”有一个
程序错误。

断言在大型、复杂的程序和
在高可靠性程序中。 它们使程序员能够更快地
清除不匹配的接口假设、修改代码时出现的错误等等。

断言通常需要两个参数:一个布尔表达式,
描述了应该为真的假设以及一条消息
如果不是则显示。

(…)

通常,您不希望用户看到断言消息
生产代码; 断言主要用于开发期间使用
和维护。 断言通常编译到代码中
开发时间并编译出用于生产的代码。 期间
发展,断言冲走矛盾的假设,
意外情况、传递给例程的错误值等等。
在生产过程中,它们是从代码中编译出来的,以便
断言不会降低系统性能。

From Code Complete

8 Defensive Programming

8.2 Assertions

An assertion is code that’s used during development—usually a routine
or macro—that allows a program to check itself as it runs. When a
assertion is true, that means everything is operating as expected.
When it’s false, that means it has detected an unexpected error in the
code. For example, if the system assumes that a customer-information
file will never have more than 50,000 records, the program might
contain an assertion that the number of records is less than or equal
to 50,000. As long as the number of records is less than or equal to
50,000, the assertion will be silent. If it encounters more than
50,000 records, however, it will loudly “assert” that there is a
error in the program.

Assertions are especially useful in large, complicated programs and
in high-reliability programs. They enable programmers to more quickly
flush out mismatched interface assumptions, errors that creep in when the code is modified, and so on.

An assertion usually takes two arguments: a boolean expression that
describes the assumption that’s supposed to be true and a message to
display if it isn’t.

(…)

Normally, you don’t want users to see assertion messages in
production code; assertions are primarily for use during development
and maintenance. Assertions are normally compiled into the code at
development time and compiled out of the code for production. During
development, assertions flush out contradictory assumptions,
unexpected conditions, bad values passed to routines, and so on.
During production, they are compiled out of the code so that the
assertions don’t degrade system performance.

审判长 2024-07-12 20:57:32

当您不想在每一小行代码中设置断点来检查变量,但您确实希望在出现某些情况时获得某种反馈时,您应该使用它,例如:

Debug.Assert(someObject != null, "someObject is null! this could totally be a bug!");

You should use it for times when you don't want to have to breakpoint every little line of code to check variables, but you do want to get some sort of feedback if certain situations are present, for example:

Debug.Assert(someObject != null, "someObject is null! this could totally be a bug!");
花落人断肠 2024-07-12 20:57:32

首先,Assert() 方法可用于 TraceDebug 类。
Debug.Assert() 仅在调试模式下执行。
Trace.Assert() 在调试和发布模式下执行。

下面是一个示例:

        int i = 1 + 3;
        // Debug.Assert method in Debug mode fails, since i == 4
        Debug.Assert(i == 3);
        Debug.WriteLine(i == 3, "i is equal to 3");

        // Trace.Assert method in Release mode is not failing.
        Trace.Assert(i == 4);
        Trace.WriteLine(i == 4, "i is equla to 4");

        Console.WriteLine("Press a key to continue...");
        Console.ReadLine();

在调试模式下运行此代码,然后在发布模式下运行。

在此处输入图像描述

您会注意到,在调试模式下,您的代码 Debug.Assert 语句失败,您会看到一个消息框,显示应用程序的当前堆栈跟踪。 在发布模式下不会发生这种情况,因为 Trace.Assert() 条件为 true (i == 4)

WriteLine()方法只是为您提供了将信息记录到 Visual Studio 输出的选项。
输入图像描述这里

First of all Assert() method is available for Trace and Debug classes.
Debug.Assert() is executing only in Debug mode.
Trace.Assert() is executing in Debug and Release mode.

Here is an example:

        int i = 1 + 3;
        // Debug.Assert method in Debug mode fails, since i == 4
        Debug.Assert(i == 3);
        Debug.WriteLine(i == 3, "i is equal to 3");

        // Trace.Assert method in Release mode is not failing.
        Trace.Assert(i == 4);
        Trace.WriteLine(i == 4, "i is equla to 4");

        Console.WriteLine("Press a key to continue...");
        Console.ReadLine();

Run this code in Debug mode and then in Release mode.

enter image description here

You will notice that during Debug mode your code Debug.Assert statement fails, you get a message box showing the current stack trace of the application. This is not happening in Release mode since Trace.Assert() condition is true (i == 4).

WriteLine() method simply gives you an option of logging the information to Visual Studio output.
enter image description here

长途伴 2024-07-12 20:57:32

Assert 还为您提供了另一个嘲笑 Microsoft UI 设计技巧的机会。 我的意思是:一个带有三个按钮“中止”、“重试”、“忽略”的对话框,以及如何在标题栏中解释它们的说明!

Assert also gives you another opportunity to chuckle at Microsoft's UI design skills. I mean: a dialog with three buttons Abort, Retry, Ignore, and an explanation of how to interpret them in the title bar!

网名女生简单气质 2024-07-12 20:57:32

断言允许您断言代码中适用的条件(后或前)。 这是一种记录您的意图的方法,如果您的意图未得到满足,调试器会通过对话框通知您。

与断点不同,断言与您的代码一起使用,可用于添加有关您的意图的其他详细信息。

Assert allows you to assert a condition (post or pre) applies in your code. It's a way of documenting your intentions and having the debugger inform you with a dialog if your intention is not met.

Unlike a breakpoint, the Assert goes with your code and can be used to add additional detail about your intention.

世态炎凉 2024-07-12 20:57:32

断言可以帮助您在测试和发布之间提供单独的消息传递行为。 例如,

如果您正在运行“调试”构建,而不是发布构建,则 Debug.Assert(x > 2)

只会触发中断。
这里有一个完整的示例

Assert can help you give separate messaging behavior between testing and release. For example,

Debug.Assert(x > 2)

will only trigger a break if you are running a "debug" build, not a release build.
There's a full example of this behavior here

挽清梦 2024-07-12 20:57:32

断言在契约设计 (DbC) 中占有重要地位,据我所知,它是由 Meyer、Bertand 引入/认可的。 1997。面向对象的软件构建。

一个重要的特性是它们不能产生副作用,例如您可以使用 if 语句处理异常或采取不同的操作过程(防御性编程)。

断言用于检查合同的前置/后置条件、客户/供应商关系 - 客户必须确保满足供应商的前置条件,例如。 发送 £5,供应商必须确保满足后置条件,例如。 送12朵玫瑰。
(只是对客户/供应商的简单解释 - 可以接受更少并交付更多,但关于断言)。
C#还引入了Trace.Assert(),可用于发布代码。

要回答这个问题,是的,它们仍然有用,但会增加代码的复杂性+可读性和时间+难以维护。
我们还应该使用它们吗? 是的,
我们都会使用它们吗? 可能不会,或者不会达到迈耶所描述的程度。

(即使是我学习这项技术的 OU Java 课程也只展示了简单的示例,其余代码并没有在大多数代码上强制执行 DbC 断言规则,而是假设用于确保程序的正确性!)

Assertions feature heavily in Design by Contract (DbC) which as I understand was introducted/endorsed by Meyer, Bertand. 1997. Object-Oriented Software Contruction.

An important feature is that they mustn't produce side-effects, for example you can handle an exception or take a different course of action with an if statement(defensive programming).

Assertions are used to check the pre/post conditions of the contract, the client/supplier relationship - the client must ensure that the pre-conditions of the supplier are met eg. sends £5 and the supplier must ensure the post-conditions are met eg. delivers 12 roses.
(Just simple explanation of client/supplier - can accept less and deliver more, but about Assertions).
C# also introduces Trace.Assert(), which can be used for release code.

To answer the question yes they still useful, but can add complexity+readability to code and time+difficultly to maintain.
Should we still use them? Yes,
Will we all use them? Probably not, or not to the extent of how Meyer describes.

(Even the OU Java course that I learnt this technique on only showed simple examples and the rest of there code didn't enforce the DbC assertion rules on most of code, but was assumed to be used to assure program correctness!)

习ぎ惯性依靠 2024-07-12 20:57:32

我认为 Debug.Assert 是一种建立关于如何调用方法的契约的方法,重点关注参数值的细节(而不仅仅是类型)。 例如,如果您不应该在第二个参数中发送 null,则可以在该参数周围添加 Assert 以告诉使用者不要这样做。

它可以防止某人愚蠢地使用您的代码。 但它也允许这种愚蠢的方式进入生产阶段,而不会给客户带来令人讨厌的信息(假设您构建了一个发布版本)。

The way I think of it is Debug.Assert is a way to establish a contract about how a method is supposed to be called, focusing on specifics about the values of a paramter (instead of just the type). For example, if you are not supposed to send a null in the second parameter you add the Assert around that parameter to tell the consumer not to do that.

It prevents someone from using your code in a boneheaded way. But it also allows that boneheaded way to go through to production and not give the nasty message to a customer (assuming you build a Release build).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文