Files
ww-jst/wmsjst/JSMachine.WMS.Infrastructure/Guards.cs
T
2026-09-02 16:31:50 +08:00

78 lines
3.1 KiB
C#

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