using System.Diagnostics.CodeAnalysis; namespace XFEExtension.NetCore.ArrayExtension; /// /// 对数组的拓展 /// public static class ArrayExtension { private static readonly string[] Separator = ["[+-", "-+]"]; /// /// 对数组的拓展 /// /// /// extension(T[] arrays) { /// /// 将数组转换为XFE格式字符串 /// /// public string ToXFEString() => arrays.Aggregate(string.Empty, (current, ary) => current + $"[+-{ary?.ToString()?.Replace("[+", "[++").Replace("+]", "++]")}-+]"); } /// /// 对数组的拓展 /// /// /// extension(T[] arrays) where T : class { /// /// 读取数组中每个对象的指定属性值,并将这些值转换为 XFE 格式字符串。 /// /// 属性名称 /// 由各对象指定属性值组成的 XFE 格式字符串。 public string ToXFEString(string propertyName) => arrays.Aggregate(string.Empty, (current, ary) => current + $"[+-{ary.GetType().GetProperty(propertyName)?.GetValue(ary)?.ToString()?.Replace("[+", "[++").Replace("+]", "++]")}-+]"); } /// extension(string str) { /// /// 将XFE格式字符串转换为数组 /// /// /// T类型的数组 public T[] ToXFEArray() { var strings = str.Split(Separator, StringSplitOptions.RemoveEmptyEntries); for (var i = 0; i < strings.Length; i++) { strings[i] = strings[i].Replace("[++", "[+").Replace("++]", "+]"); } var array = new T[(strings.Length - 1) / 2]; for (int i = 0, j = 1; i < array.Length; i++, j += 2) { array[i] = (T)Convert.ChangeType(strings[j], typeof(T)); } return array; } } /// extension(object[]? objects) { /// /// 获取数组中的类型 /// /// [return: NotNullIfNotNull(nameof(objects))] public Type[]? GetTypes() { if (objects is null) return null; var types = new Type[objects.Length]; for (var i = 0; i < objects.Length; i++) { types[i] = objects[i].GetType(); } return types; } } }