C# - Assert() 方法有什么作用?它还有用吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/163538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# - What does the Assert() method do? Is it still useful?
提问by Pokus
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?
我正在使用断点进行调试并且我实现了断言调用?我以为它只用于单元测试。除了断点,它还能做什么?既然可以断点,那为什么要使用Assert呢?
采纳答案by Patrick Desjardins
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.
在调试编译中,Assert
接受一个布尔条件作为参数,如果条件为假则显示错误对话框。如果条件为真,则程序继续进行而不会中断。
If you compile in Release, all Debug.Assert
's are automatically left out.
如果您在 Release 中编译,则所有Debug.Assert
's 都会自动被排除在外。
回答by Jeff Yates
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.
与断点不同,断言与您的代码一起使用,可用于添加有关您的意图的其他详细信息。
回答by Ryan
Assert can help you give separate messaging behavior between testing and release. For example,
断言可以帮助您在测试和发布之间提供单独的消息传递行为。例如,
Debug.Assert(x > 2)
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
如果您正在运行“调试”版本,则只会触发中断,而不是发布版本。有此行为的完整的例子在这里
回答by thelsdj
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!");
回答by Joe
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!
Assert 还让您有机会对 Microsoft 的 UI 设计技巧嗤之以鼻。我的意思是:一个包含三个按钮 Abort、Retry、Ignore 的对话框,以及如何在标题栏中解释它们的解释!
回答by juan
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.
8 防御性编程
8.2 断言
断言是在开发过程中使用的代码——通常是一个例程或宏——它允许程序在运行时自我检查。当断言为真时,这意味着一切都按预期运行。当它为 false 时,这意味着它在代码中检测到了意外错误。例如,如果系统假定客户信息文件的记录永远不会超过 50,000,则程序可能包含记录数小于或等于 50,000 的断言。只要记录数小于或等于 50,000,断言就会静默。但是,如果遇到超过 50,000 条记录,它会大声“断言”程序中存在错误。
断言在大型复杂程序和高可靠性程序中特别有用。它们使程序员能够更快地清除不匹配的接口假设、修改代码时潜入的错误等。
断言通常采用两个参数:一个布尔表达式,描述应该为真的假设,如果不是,则显示一条消息。
(…)
通常,您不希望用户在生产代码中看到断言消息;断言主要用于开发和维护期间。断言通常在开发时编译到代码中,并从代码中编译出来用于生产。在开发过程中,断言会清除相互矛盾的假设、意外情况、传递给例程的错误值等。在生产过程中,它们是从代码中编译出来的,这样断言就不会降低系统性能。
回答by Flory
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.
我认为它的方式是 Debug.Assert 是一种建立关于应该如何调用方法的契约的方法,专注于关于参数值的细节(而不仅仅是类型)。例如,如果您不应该在第二个参数中发送 null,则在该参数周围添加 Assert 以告诉消费者不要这样做。
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).
它可以防止有人以愚蠢的方式使用您的代码。但它也允许这种笨拙的方式进入生产,而不是向客户传达令人讨厌的信息(假设您构建了一个发布版本)。
回答by Knightlore
Assertions feature heavily in Design by Contract (DbC) which as I understand was introducted/endorsed by Meyer, Bertand. 1997. Object-Oriented Software Contruction.
断言在契约设计 (DbC) 中占有重要地位,据我所知,它是由 Meyer, Bertand 引入/认可的。1997. 面向对象的软件构造。
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).
一个重要的特性是它们不能产生副作用,例如您可以使用 if 语句处理异常或采取不同的行动方案(防御性编程)。
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.
断言用于检查合同的前/后条件、客户/供应商关系 - 客户必须确保满足供应商的先决条件,例如。发送£5,供应商必须确保满足后置条件,例如。送出 12 朵玫瑰。(只是对客户/供应商的简单解释 - 可以接受更少并提供更多,但关于断言)。C# 还引入了 Trace.Assert(),可用于发布代码。
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!)
(即使是我学习这项技术的 OU Java 课程也只展示了简单的示例,其余代码并未对大多数代码强制执行 DbC 断言规则,而是假定用于确保程序正确性!)
回答by Serge Voloshenko
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.
首先,Assert()
方法可用于Trace
和Debug
类。Debug.Assert()
仅在调试模式下执行。Trace.Assert()
正在调试和发布模式下执行。
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.
在调试模式下运行此代码,然后在发布模式下运行。
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)
.
您会注意到,在调试模式下,您的代码Debug.Assert
语句失败,您会收到一个消息框,显示应用程序的当前堆栈跟踪。这在 Release 模式Trace.Assert()
下不会发生,因为条件为 true (i == 4)
。
WriteLine()
method simply gives you an option of logging the information to Visual Studio output.