wcs_serve_wuxikate/WcsMain/ExtendMethod/StringExtendMethod.cs
2025-01-03 14:36:27 +08:00

100 lines
2.7 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using HslCommunication;
using System.Text.RegularExpressions;
namespace WcsMain.ExtendMethod;
/// <summary>
/// 扩展方法,检查基础数据
/// </summary>
public static partial class StringExtendMethod
{
/// <summary>
/// 检测一个字符串是不是 NoRead
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static bool IsNoRead(this string? value)
{
if (string.IsNullOrEmpty(value)) return false;
return value.Replace(" ", "").Equals("noread", StringComparison.CurrentCultureIgnoreCase);
}
/// <summary>
/// 检查一个字符串是否是数字
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static bool IsNumber(this string? value)
{
if (string.IsNullOrEmpty(value)) return false;
return IsNumberRegex().IsMatch(value);
}
/// <summary>
/// 将字符串转换为 bool只有等于null和0的情况下是false
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static bool ToBool(this string? value)
{
if(value == null) return false;
return value != "0";
}
/// <summary>
/// 检测一个字符串是不是时间格式,如果是返回时间,如果不是返回 default
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static DateTime? ToDateTime(this string? value)
{
try
{
DateTime time = Convert.ToDateTime(value);
return time;
}
catch
{
return default;
}
}
/// <summary>
/// 格式化条码,返回条码和方位码
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
[Obsolete("客户变更需求,不使用方向码", true)]
public static (string code, string direction) FormatDir(this string? value)
{
if (string.IsNullOrEmpty(value)) return (string.Empty, string.Empty);
string[] vals = value.Split('-');
if (vals.Length < 2) return (value, string.Empty);
string direction = vals[^1];
string code = value.RemoveLast(direction.Length + 1);
return (code, direction);
}
/// <summary>
/// 将载具号转换为 plc 可识别的载具号
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static int ToPlcVehicleNo(this string? value)
{
if (string.IsNullOrEmpty(value)) return 0;
try
{
return Convert.ToInt32(Regex.Replace(value, "\\D", ""));
}
catch
{
return 0;
}
}
[GeneratedRegex("^\\d+$")]
private static partial Regex IsNumberRegex();
}