using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace JSMachine.DCS.Infrastructure { /// /// 基础参数守卫工具,在进入业务流程前校验空值、路径和条件状态。 /// public static class Guards { /// 当任意参数为空时抛出参数异常。 /// 待检查的参数集合。 public static void ThrowIfNull(params object[] parameters) { if (parameters.Any(item => item == null)) throw new ArgumentNullException(); } /// 当任意字符串为空或空字符串时抛出参数异常。 /// 待检查的字符串集合。 public static void ThrowIfNullOrEmpty(params string[] strings) { if (strings.Any(string.IsNullOrEmpty)) throw new ArgumentNullException(); } /// 检查字符串序列及其中的每一项是否为空。 /// 待检查的字符串序列。 public static void ThrowIfNullOrEmpty(IEnumerable strings) { ThrowIfNull(strings); ThrowIfNullOrEmpty(strings.ToArray()); } /// 当指定文件不存在时抛出文件未找到异常。 /// 文件路径。 public static void ThrowIfFileNotFound(string path) { if (!File.Exists(path)) throw new FileNotFoundException("Can not found the specified file path. ", path); } /// 当指定目录不存在时抛出目录未找到异常。 /// 目录路径。 public static void ThrowIfFolderNotFount(string path) { if (!Directory.Exists(path)) throw new DirectoryNotFoundException($"Can not found the specified path {path}. "); } /// 当路径既不是文件也不是目录时抛出目录异常。 /// 待检查的路径。 public static void ThrowIfInvalidPath(string path) { if (!File.Exists(path) && !Directory.Exists(path)) throw new DirectoryNotFoundException($"The specified path is not a valid file or directory. ({path})"); } /// 当条件不成立时抛出无效操作异常。 /// 必须成立的条件。 public static void ThrowIfNot(bool condition) { if (!condition) throw new InvalidOperationException(); } /// 计算条件并在结果不成立时抛出无效操作异常。 /// 返回校验结果的委托。 public static void ThrowIfNot(Func condition) { ThrowIfNull(condition); ThrowIfNot(condition()); } } }