C# Assert
最后修改:2025 年 2 月 15 日
在本文中,我们将展示如何在 C# 中使用 Assert
类。 Assert
类是 System.Diagnostics
命名空间的一部分,用于调试和测试以验证条件。如果未满足条件,Assert
方法将抛出异常,帮助您识别代码中的问题。
Assert
类对于单元测试和调试特别有用,因为它允许您验证假设并在开发过程的早期捕获错误。
Assert 的基本用法
以下示例演示如何使用 Assert
类来验证条件。
Program.cs
int x = 10; int y = 20; // Assert that x is less than y Debug.Assert(x < y, "x should be less than y"); Console.WriteLine("Assertion passed.");
在此程序中,Debug.Assert
方法用于验证 x
小于 y
。如果条件为假,程序将抛出一个带有指定消息的异常。
$ dotnet run Assertion passed.
如果条件不满足,程序将输出
$ dotnet run Debug Assertion Failed: x should be less than y
带有自定义消息的 Assert
以下示例演示如何使用带有自定义错误消息的 Assert
类。
Program.cs
int age = 15; // Assert that age is greater than or equal to 18 Debug.Assert(age >= 18, "Age must be at least 18"); Console.WriteLine("Assertion passed.");
在此程序中,Debug.Assert
方法用于验证 age
大于或等于 18。如果条件为假,程序将抛出一个带有指定消息的异常。
$ dotnet run Debug Assertion Failed: Age must be at least 18
带有复杂条件的 Assert
以下示例演示如何使用带有复杂条件的 Assert
类。
Program.cs
string name = "Alice"; int length = name.Length; // Assert that the name is not null and has a length greater than 0 Debug.Assert(!string.IsNullOrEmpty(name) && length > 0, "Name must not be null or empty"); Console.WriteLine("Assertion passed.");
在此程序中,Debug.Assert
方法用于验证 name
不为空且长度大于 0。如果条件为假,程序将抛出一个异常。
$ dotnet run Assertion passed.
禁用断言
默认情况下,断言仅在调试版本中处于活动状态。要禁用断言,您可以定义 DEBUG
常量或使用 Conditional
属性。以下示例演示如何禁用断言。
Program.cs
#define DEBUG // Comment this line to disable assertions using System.Diagnostics; int x = 10; int y = 5; // Assert that x is less than y Debug.Assert(x < y, "x should be less than y"); Console.WriteLine("Assertion passed.");
在此程序中,定义了 DEBUG
常量以启用断言。 如果您注释掉 #define DEBUG
行,断言将被禁用,并且程序将不会抛出异常。
$ dotnet run Debug Assertion Failed: x should be less than y
来源
在本文中,我们展示了如何在 C# 中使用 Assert
类进行调试和测试。 Assert
类是一个强大的工具,用于验证条件并在开发过程的早期捕获错误。
作者
列出所有 C# 教程。