GuardClauses
Ardalis.GuardClauses
https://www.nuget.org/packages/Ardalis.GuardClauses
https://github.com/ardalis/guardclauses
Guard.Against.Null
→ 若输入为 null,则抛出异常
Guard.Against.NullOrEmpty
→ 若输入(字符串、Guid 或数组)为 null 或空(长度为 0),则抛出异常
Guard.Against.NullOrWhiteSpace
→ 若输入(字符串)为 null、空或仅包含空白字符(如空格、制表符、换行符),则抛出异常
Guard.Against.OutOfRange
→ 若输入(整数、DateTime 或枚举类型)超出指定范围,则抛出异常
Guard.Against.EnumOutOfRange
→ 若输入的枚举值不在指定的有效枚举值范围内,则抛出异常
Guard.Against.OutOfSQLDateRange
→ 若输入(DateTime)超出 SQL Server `datetime` 类型的有效范围(1753-01-01 至 9999-12-31),则抛出异常
Guard.Against.Zero
→ 若输入(数值类型)为零,则抛出异常
Guard.Against.Expression
→ 使用自定义表达式进行校验;若表达式返回 `false`,则抛出异常
Guard.Against.InvalidFormat
→ 通过正则表达式或自定义函数校验格式;若不符合指定格式,则抛出异常
Guard.Against.NotFound
→ 用于 ID/键值查找场景(如数据库查询);若未找到对应实体,则抛出 `NotFoundException`(语义上比 `Null` 更明确)
# 扩展
public static void Foo(this IGuardClause guardClause,
string input,
[CallerArgumentExpression("input")] string? parameterName = null)
{
if (input?.ToLower() == "foo")
throw new ArgumentException("Should not have been foo!", parameterName);
}
以前用的
CuttingEdge.Conditions
https://www.nuget.org/packages/CuttingEdge.Conditions.NetStandard
https://blog.xsoft.ltd/2025/02/07/cuttingedge-conditions-%e6%9b%bf%e4%bb%a3/