using HighWayIot.Plc; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace HighWayIot.Winform.Business { public class GeneralUtils { /// /// 在字符串数组前面加一个空字符串 /// /// public static string[] HeadAddEmptyString(string[] str) { Array.Resize(ref str, str.Length + 1); Array.Copy(str, 0, str, 1, str.Length - 1); str[0] = string.Empty; return str; } /// /// 转换string为int /// /// /// public static int? StringNullOrToInt(string text) { return int.TryParse(text, out int result) ? (int?)result : null; } public static string IntEmptyOrToString(int? value) { if (value == null) { return string.Empty; } else { return value.ToString(); } } /// /// 返回对应的枚举类Type类型 /// /// /// /// public static Type GetTypeByEnum(DataTypeEnum type) { switch (type) { case DataTypeEnum.Bool: return typeof(bool); case DataTypeEnum.Byte: return typeof(byte); case DataTypeEnum.Int16: return typeof(short); case DataTypeEnum.UInt16: return typeof(ushort); case DataTypeEnum.Int32: return typeof(int); case DataTypeEnum.UInt32: return typeof(uint); case DataTypeEnum.Int64: return typeof(long); case DataTypeEnum.UInt64: return typeof(ulong); case DataTypeEnum.Float: return typeof(float); case DataTypeEnum.Double: return typeof(double); default: return default; } } /// /// 获取枚举类的键值对 /// /// /// public static IEnumerable> GetEnumKeyValuePairs() where T : Enum { var enumType = typeof(T); var fields = enumType.GetFields(); foreach (var fi in fields) { if (fi.FieldType != enumType || !fi.IsLiteral) continue; var name = fi.Name; var value = (int)enumType.GetField(name).GetValue(null); yield return new KeyValuePair(name, value); } } /// /// 获取枚举类值的description元数据(没有Des返回名字) /// /// public static string GetEnumStringDescription(Enum enumValue) { string value = enumValue.ToString(); FieldInfo field = enumValue.GetType().GetField(value); object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); //获取描述属性 if (objs.Length == 0) //当描述属性没有时,直接返回名称 return value; DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0]; return descriptionAttribute.Description; } } }