diff --git a/anbs_cp/FileSizeFormatter.cs b/anbs_cp/FileSizeFormatter.cs index a3ed3e2..a4cbd33 100644 --- a/anbs_cp/FileSizeFormatter.cs +++ b/anbs_cp/FileSizeFormatter.cs @@ -1,78 +1,56 @@ -using System; -namespace anbs_cp +namespace anbs_cp { /// /// Форматирует размер файла/папки в понятную строку /// - public static class FileSizeFormatter + public class FileSizeFormatter : IValueFormatter { + #region Cвойства класса /// /// Имена размеров (байт, килобайт, мегабайт, гигабайт и террабайт) /// - public static string[] SizeNames { get; set; } = { "Байт", "Кб", "Мб", "Гб", "Тб" }; + public string[] SizeNames { get; set; } = { "Байт", "Кб", "Мб", "Гб", "Тб" }; /// /// Знаков после запятой /// - public static byte DecimalPlaces { get; set; } = 2; + public byte DecimalPlaces { get; set; } = 2; /// /// Максимально байт (далее идут Кбайты) /// - public static long ByteMax { get; set; } = 1024; + public long ByteMax { get; set; } = 1024; /// /// Максимально Кбайт (далее идут Мбайты) /// - public static long KByteMax { get; set; } = 1048576; + public long KByteMax { get; set; } = 1048576; /// /// Максимально Мбайт (далее идут Гбайты) /// - public static long MByteMax { get; set; } = 1073741824; + public long MByteMax { get; set; } = 1073741824; /// /// Максимально Гбайт (далее идут Тбайты) /// - public static long GByteMax { get; set; } = 1099511627776; - /// - /// Форматирование размера файла - /// - /// Размер файла в Байтах - /// Форматированный размер файла (например, 20 Мб) - public static string Format(long value) - { - //Bytes - if (value < ByteMax) - return $"{value} {SizeNames[0]}"; - //KiloBytes - if ((value >= ByteMax) && (value < KByteMax)) - return $"{FrmtSize(value, ByteMax)} {SizeNames[1]}"; - //MegaBytes - if ((value >= KByteMax) && (value < MByteMax)) - return $"{FrmtSize(value, KByteMax)} {SizeNames[2]}"; - //GigaBytes - if ((value >= MByteMax) && (value < GByteMax)) - return $"{FrmtSize(value, MByteMax)} {SizeNames[3]}"; - //TeraBytes - if (value >= GByteMax) - return $"{FrmtSize(value, GByteMax)} {SizeNames[4]}"; - //Не определён - return $"{value} {SizeNames[0]}"; - } - /// - /// Деление числа на число с DecimalPlaces знаками после запятой - /// - /// Делимое число - /// Число-делитель - /// Частное (с DecimalPlaces знаками после запятой) - private static string FrmtSize(long dividend, long divider) - { - long delim = 1; + public long GByteMax { get; set; } = 1099511627776; + #endregion - for (int i = 0; i <= DecimalPlaces; i++) + #region Реализация интерфейса + /// + /// Реализация интерфейса + /// + public string[] ValueNames { get => SizeNames; set => SizeNames = value; } + /// + /// Реализация интерфейса + /// + public long[] MaxSizes + { + get => new long[] { ByteMax, KByteMax, MByteMax, GByteMax }; + set { - delim *= 10; + ByteMax = value[0]; + KByteMax = value[1]; + MByteMax = value[2]; + GByteMax = value[3]; } - - decimal value = Math.Round((decimal)(dividend * delim / divider)) / delim; - - return $"{value}"; } + #endregion } } \ No newline at end of file diff --git a/anbs_cp/IValueFormatter.cs b/anbs_cp/IValueFormatter.cs new file mode 100644 index 0000000..510d18e --- /dev/null +++ b/anbs_cp/IValueFormatter.cs @@ -0,0 +1,71 @@ +namespace anbs_cp +{ + /// + /// Форматирует размерности в понятную строку + /// + public interface IValueFormatter + { + + #region Определения интерфейса + /// + /// Имена размерностей + /// + public string[] ValueNames { get; set; } + /// + /// Знаков после запятой + /// + public byte DecimalPlaces { get; set; } + /// + /// Максимальные размеры (массив ulong[4]) + /// + public long[] MaxSizes { get; set; } + #endregion + + #region Методы интерфейса + /// + /// Форматирование размерности + /// + /// Размерность, требующая форматирования + /// Форматированная размерность (например, 20 Мб) + public string Format(long value) + { + //Bytes + if (value < MaxSizes[0]) + return $"{value} {ValueNames[0]}"; + //KiloBytes + if ((value >= MaxSizes[0]) && (value < MaxSizes[1])) + return $"{FrmtSize(value, MaxSizes[0])} {ValueNames[1]}"; + //MegaBytes + if ((value >= MaxSizes[1]) && (value < MaxSizes[2])) + return $"{FrmtSize(value, MaxSizes[1])} {ValueNames[2]}"; + //GigaBytes + if ((value >= MaxSizes[2]) && (value < MaxSizes[3])) + return $"{FrmtSize(value, MaxSizes[2])} {ValueNames[3]}"; + //TeraBytes + if (value >= MaxSizes[3]) + return $"{FrmtSize(value, MaxSizes[3])} {ValueNames[4]}"; + //Не определён + return $"{value} {ValueNames[0]}"; + } + /// + /// Деление числа на число с DecimalPlaces знаками после запятой + /// + /// Делимое число + /// Число-делитель + /// Частное (с DecimalPlaces знаками после запятой) + private string FrmtSize(long dividend, long divider) + { + long delim = 1; + + for (int i = 0; i <= DecimalPlaces; i++) + { + delim *= 10; + } + + decimal value = Math.Round((decimal)(dividend * delim / divider)) / delim; + + return $"{value}"; + } + #endregion + } +} \ No newline at end of file diff --git a/anbs_cp/LikeDelphi.cs b/anbs_cp/LikeDelphi.cs index 42be5e9..bf6831d 100644 --- a/anbs_cp/LikeDelphi.cs +++ b/anbs_cp/LikeDelphi.cs @@ -1,39 +1,47 @@ using System.Collections.Generic; - namespace anbs_cp { + /// + /// Класс, добавляющий реализацию некоторых методов Delphi, которые упрощают работу в C#. + /// public static class LikeDelphi { - /* - * Аналог функции "IncludeTrailingBackslash - */ - public static string IncludeTrailingBackslash(string Path) + /// + /// Аналог функции IncludeTrailingBackslash + /// + /// Путь, к которому нужно добавить slash + /// Путь со slash в конце + public static string IncludeTrailingBackslash(string path) { - string result = Path; - int Index = Path.Length - 1; - if (Path[Index] != '\\') + string result = path; + int Index = path.Length - 1; + if (path[Index] != '\\') { - result = $"{Path}\\"; + result = $"{path}\\"; } return result; } - public static List ParseString(string AString, char ADelim) + /// + /// Парсер строки в множество строк + /// + /// Строка, которую нужно разбить + /// Символ-делитель строки + /// Массив строк + public static List ParseString(string astring, char delim) { int from = -1; - int to = AString.Length; - List result = new List(); + int to; + List result = new(); do { from++; - to = AString.IndexOf(ADelim, from); + to = astring.IndexOf(delim, from); if (to <= 0) - { - to = AString.Length; - } + to = astring.Length; if (from != to) - result.Add(AString.Substring(from, to - from)); + result.Add(astring[from..(to-from)]); from = to; - } while (to != AString.Length); + } while (to != astring.Length); return result; } } diff --git a/anbs_cp/TStringList.cs b/anbs_cp/TStringList.cs deleted file mode 100644 index 596556d..0000000 --- a/anbs_cp/TStringList.cs +++ /dev/null @@ -1,164 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; - -namespace anbs_componentspack -{ - public enum TStringListType - { - sltStringsOnly, //Только строки -- сортировка по строкам включена, имеющиеся объекты удалит - sltObjectsOnly, //Только объекты -- сортировка по объектам включена - sltBoth //И строки, и объекты -- сортировка отключена - } - public class TStringList - { - private List FLines; - private List FObjects; - private TStringListType type = TStringListType.sltBoth; - public TStringListType Type { get => type; set => type = value; } - public int Count => FLines.Count; - public override bool Equals(object obj) - { - return obj is TStringList list && - Count == list.Count; - } - public override int GetHashCode() - { - return HashCode.Combine(Count); - } - public void Add(string AString) - { - if (!(type == TStringListType.sltObjectsOnly)) - { - FLines.Add(AString); - if (!(type == TStringListType.sltStringsOnly)) - { - FObjects.Add(AString); - } - } - } - public void Add(object AObject) - { - if (!(type == TStringListType.sltStringsOnly)) - { - if (!(type == TStringListType.sltObjectsOnly)) - { - FLines.Add(AObject.ToString()); - - } - FObjects.Add(AObject); - } - } - public void Add(string AString, object AObject) - { - if (!(type == TStringListType.sltStringsOnly) && !(type == TStringListType.sltObjectsOnly)) - { - FLines.Add(AString); - FObjects.Add(AObject); - } - } - public (string, object) Get(int Index) => (FLines[Index], FObjects[Index]); - public string GetString(int Index) - { - string result = ""; - if (!(type == TStringListType.sltObjectsOnly)) - { - result = FLines[Index]; - } - return result; - } - public object GetObject(int Index) - { - object result = null; - if (!(type == TStringListType.sltStringsOnly)) - { - result = FObjects[Index]; - } - return result; - } - public void Delete(int Index) - { - if (!(type == TStringListType.sltObjectsOnly)) - { - FLines.RemoveAt(Index); - } - if (!(type == TStringListType.sltStringsOnly)) - { - FObjects.RemoveAt(Index); - } - } - public int IndexOf(string AString) => FLines.IndexOf(AString); - public int IndexOf(object AObject) => FObjects.IndexOf(AObject); - public void Sort() - { - switch (type) - { - case TStringListType.sltStringsOnly: - FLines.Sort(); - break; - case TStringListType.sltObjectsOnly: - FObjects.Sort(); - break; - case TStringListType.sltBoth: - break; - default: - break; - } - } - public void Clear() - { - FLines.Clear(); - FObjects.Clear(); - } - public void Assign(List ALines) - { - if (!(type == TStringListType.sltStringsOnly)) - { - throw new ArgumentException("Assign method works in TStringList only for the sltStringsOnly type. Your changes are not applied!"); - } - Clear(); - FLines.AddRange(ALines); - } - public string DelimetedText(char Delimeter) - { - string result = ""; - if (!(type == TStringListType.sltObjectsOnly)) - { - for (int i = 0; i < FLines.Count; i++) - { - result = $"{result}{Delimeter}{FLines[i]}"; - } - } - return result; - } - public string Text() - { - char Delim = '\n'; - return DelimetedText(Delim); - } - public void LoadFromFile(string FileName) - { - if (!File.Exists(FileName)) - { - throw new FileNotFoundException(); - } - StreamReader sr = new StreamReader(FileName); - string line = sr.ReadLine(); - while (line != null) - { - FLines.Add(line); - line = sr.ReadLine(); - } - sr.Close(); - } - public void SaveToFile(string FileName) - { - StreamWriter sw = new StreamWriter(FileName); - for (int i = 0; i < FLines.Count; i++) - { - sw.WriteLine(FLines[i]); - } - sw.Close(); - } - } -} diff --git a/anbs_cp/TypeConverter.cs b/anbs_cp/TypeConverter.cs index f5485b8..3ab4951 100644 --- a/anbs_cp/TypeConverter.cs +++ b/anbs_cp/TypeConverter.cs @@ -1,9 +1,50 @@ -namespace anbs_componentspack +namespace anbs_cp { + /// + /// Конвертер типов на манер Delphi + /// public static class TypeConverter { + #region Конвертация числа в строку + /// + /// Преобразование int в string + /// + /// Число + /// Строка public static string IntToStr(int AInt) => AInt.ToString(); + /// + /// Преобразование uint в string + /// + /// Число + /// Строка + public static string IntToStr(uint AInt) => AInt.ToString(); + /// + /// Преобразование long в string + /// + /// Число + /// Строка public static string IntToStr(long AInt) => AInt.ToString(); + /// + /// Преобразование ulong в string + /// + /// Число + /// Строка + public static string IntToStr(ulong AInt) => AInt.ToString(); + /// + /// Преобразование byte в string + /// + /// Число + /// Строка + public static string IntToStr(byte AInt) => AInt.ToString(); + #endregion + + #region Конвертация строки в число + /// + /// Преобразование строки в число + /// + /// Строка + /// Значение по умолчанию (по умолчанию, 0) + /// Число public static int StrToInt(string AStr, int ADefault = 0) { if (!int.TryParse(AStr, out int result)) @@ -12,6 +53,26 @@ } return result; } + /// + /// Преобразование строки в число + /// + /// Строка + /// Значение по умолчанию (по умолчанию, 0) + /// Число + public static uint StrToUInt(string AStr, uint ADefault = 0) + { + if (!uint.TryParse(AStr, out uint result)) + { + result = ADefault; + } + return result; + } + /// + /// Преобразование строки в число + /// + /// Строка + /// Значение по умолчанию (по умолчанию, 0) + /// Число public static long StrToInt64(string AStr, long ADefault = 0) { if (!long.TryParse(AStr, out long result)) @@ -20,5 +81,34 @@ } return result; } + /// + /// Преобразование строки в число + /// + /// Строка + /// Значение по умолчанию (по умолчанию, 0) + /// Число + public static ulong StrToUInt64(string AStr, ulong ADefault = 0) + { + if (!ulong.TryParse(AStr, out ulong result)) + { + result = ADefault; + } + return result; + } + /// + /// Преобразование строки в число + /// + /// Строка + /// Значение по умолчанию (по умолчанию, 0) + /// Число + public static byte StrToByte(string AStr, byte ADefault = 0) + { + if (!byte.TryParse(AStr, out byte result)) + { + result = ADefault; + } + return result; + } + #endregion } -} +} \ No newline at end of file diff --git a/anbs_cp/anbs_cp.csproj b/anbs_cp/anbs_cp.csproj index 7e7517f..f7f326e 100644 --- a/anbs_cp/anbs_cp.csproj +++ b/anbs_cp/anbs_cp.csproj @@ -1,12 +1,32 @@ - netcoreapp3.1 - 0.1.0 + net6.0-windows + 1.20211111.0 Alexander Babaev ANB Software Components Pack Library of some useful functions in C# language. - + Alexander Babaev + anbs_cp + anbs_cp + enable + enable + True + False + https://github.com/GoodBoyAlex/anbsoftware_componentspack + https://github.com/GoodBoyAlex/anbsoftware_componentspack + 1.2021.1111 + 1.2021.1111 + + + + 2 + True + + + + 2 + True