using System.Runtime.CompilerServices; namespace GFramework.Core.Extensions; /// /// 参数验证扩展方法(Guard 模式) /// public static class GuardExtensions { /// /// 如果值为 null 则抛出 ArgumentNullException /// /// 引用类型 /// 要检查的值 /// 参数名称(自动捕获) /// 非 null 的值 /// 当 value 为 null 时抛出 /// /// /// public void Process(string? input) /// { /// var safeInput = input.ThrowIfNull(); // 自动使用 "input" 作为参数名 /// } /// /// public static T ThrowIfNull( this T? value, [CallerArgumentExpression(nameof(value))] string? paramName = null) where T : class { ArgumentNullException.ThrowIfNull(value, paramName); return value; } /// /// 如果字符串为 null 或空则抛出 ArgumentException /// /// 要检查的字符串 /// 参数名称(自动捕获) /// 非空字符串 /// 当 value 为 null 时抛出 /// 当 value 为空字符串时抛出 /// /// /// public void SetName(string? name) /// { /// var safeName = name.ThrowIfNullOrEmpty(); /// } /// /// public static string ThrowIfNullOrEmpty( this string? value, [CallerArgumentExpression(nameof(value))] string? paramName = null) { ArgumentNullException.ThrowIfNull(value, paramName); if (value.Length == 0) throw new ArgumentException("字符串不能为空", paramName); return value; } /// /// 如果字符串为 null、空或仅包含空白字符则抛出 ArgumentException /// /// 要检查的字符串 /// 参数名称(自动捕获) /// 非空白字符串 /// 当 value 为 null 时抛出 /// 当 value 为空或仅包含空白字符时抛出 /// /// /// public void SetDescription(string? description) /// { /// var safeDescription = description.ThrowIfNullOrWhiteSpace(); /// } /// /// public static string ThrowIfNullOrWhiteSpace( this string? value, [CallerArgumentExpression(nameof(value))] string? paramName = null) { ArgumentNullException.ThrowIfNull(value, paramName); if (string.IsNullOrWhiteSpace(value)) throw new ArgumentException("字符串不能为空或仅包含空白字符", paramName); return value; } /// /// 如果集合为空则抛出 ArgumentException /// /// 集合元素类型 /// 要检查的集合 /// 参数名称(自动捕获) /// 非空集合 /// 当 source 为 null 时抛出 /// 当 source 为空集合时抛出 /// /// /// public void ProcessItems(IEnumerable<int>? items) /// { /// var safeItems = items.ThrowIfEmpty(); /// } /// /// public static IEnumerable ThrowIfEmpty( this IEnumerable? source, [CallerArgumentExpression(nameof(source))] string? paramName = null) { ArgumentNullException.ThrowIfNull(source, paramName); if (!source.Any()) throw new ArgumentException("集合不能为空", paramName); return source; } }