From a3ebc9f2c6868e925e38ef45265b0c5a8ccdb54c Mon Sep 17 00:00:00 2001 From: Ctepa Date: Mon, 20 May 2024 06:15:43 +0300 Subject: [PATCH 1/2] =?UTF-8?q?=D0=9F=D1=80=D0=B0=D0=BA=D1=82=D0=B8=D0=B5?= =?UTF-8?q?=D1=81=D0=BA=D0=B8=20=D0=B3=D0=BE=D1=82=D0=BE=D0=B2=D0=BE,=20?= =?UTF-8?q?=D0=BE=D0=B4=D0=BD=D0=B0=D0=BA=D0=BE=20List.Contains=20=D0=BD?= =?UTF-8?q?=D0=B5=20=D0=BC=D0=BE=D0=B6=D0=B5=D1=82=20=D0=BF=D1=80=D0=B8?= =?UTF-8?q?=D0=BD=D0=B8=D0=BC=D0=B0=D1=82=D1=8C=20=D0=B2=20=D1=81=D0=B5?= =?UTF-8?q?=D0=B1=D1=8F=20=D0=B4=D0=B2=D0=B0=20=D0=B0=D1=80=D0=B3=D1=83?= =?UTF-8?q?=D0=BC=D0=B5=D0=BD=D1=82=D0=B0((?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 8 ++- .../CollectionInfo.cs | 60 +++++++++++++++++ .../ICollectionGenericObjects.cs | 14 +++- .../ListGenericObjects.cs | 39 ++++++++--- .../MassiveGenericObjects.cs | 39 +++++++++-- .../StorageCollection.cs | 56 ++++++++-------- .../Drawnings/DrawningGunCompareByColor.cs | 28 ++++++++ .../Drawnings/DrawningGunCompareByType.cs | 35 ++++++++++ .../Drawnings/DrawningGunEqutables.cs | 64 +++++++++++++++++++ .../Exceptions/ObjectIsEqualException.cs | 16 +++++ ...cs => PositionOutOfCollectionException.cs} | 12 ++-- .../FormGunCollections.Designer.cs | 42 ++++++++++-- .../AntiAircraftGun/FormGunCollections.cs | 33 +++++++++- 13 files changed, 380 insertions(+), 66 deletions(-) create mode 100644 AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/CollectionInfo.cs create mode 100644 AntiAircraftGun/AntiAircraftGun/Drawnings/DrawningGunCompareByColor.cs create mode 100644 AntiAircraftGun/AntiAircraftGun/Drawnings/DrawningGunCompareByType.cs create mode 100644 AntiAircraftGun/AntiAircraftGun/Drawnings/DrawningGunEqutables.cs create mode 100644 AntiAircraftGun/AntiAircraftGun/Exceptions/ObjectIsEqualException.cs rename AntiAircraftGun/AntiAircraftGun/Exceptions/{PostiionOutOfCollectionException.cs => PositionOutOfCollectionException.cs} (51%) diff --git a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/AbstractCompany.cs b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/AbstractCompany.cs index 0e34fbc..f5b2651 100644 --- a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/AbstractCompany.cs +++ b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/AbstractCompany.cs @@ -51,7 +51,7 @@ public abstract class AbstractCompany /// public static bool operator +(AbstractCompany company, DrawningGun gun) { - return company._collection.Insert(gun); + return company._collection.Insert(gun,new DrawningGunEqutables()); } /// @@ -104,4 +104,10 @@ public abstract class AbstractCompany /// protected abstract void SetObjectsPosition(); + /// + /// Сортировка + /// + /// + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); + } diff --git a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/CollectionInfo.cs b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..4bb208d --- /dev/null +++ b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AntiAircraftGun.CollectionGenericObjects; + +/// +/// +/// +public class CollectionInfo:IEquatable +{ + /// + /// Имя + /// + public string Name { get; private set; } + /// + /// Тип + /// + public CollectionType CollectionType { get; private set; } + /// + /// Описание + /// + public string Description { get; private set; } + + private static readonly string _separator = "-"; + + public CollectionInfo(string name, CollectionType collectionType,string description) + { + Name = name; + CollectionType = collectionType; + Description = description; + } + + public static CollectionInfo? GetCollectionInfo(string data) + { + string[] strs=data.Split(_separator,StringSplitOptions.RemoveEmptyEntries); + if(strs.Length < 1 || strs.Length > 3) return null; + return new CollectionInfo(strs[0], + (CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ?strs[2] : string.Empty); + } + + public override string ToString() + { + return Name + _separator + CollectionType + _separator + Description; + } + public bool Equals(CollectionInfo? other) + { + return Name == other?.Name; + } + public override bool Equals(object? obj) + { + return Equals(obj as CollectionInfo); + } + public override int GetHashCode() + { + return Name.GetHashCode(); + } +} diff --git a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/ICollectionGenericObjects.cs b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/ICollectionGenericObjects.cs index 7b800b7..16af12a 100644 --- a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,4 +1,6 @@ -namespace AntiAircraftGun.CollectionGenericObjects; +using AntiAircraftGun.Drawnings; + +namespace AntiAircraftGun.CollectionGenericObjects; /// /// Интерфейс описания действий для набора хранимых объектов @@ -21,14 +23,14 @@ public interface ICollectionGenericObjects /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась - bool Insert(T obj); + bool Insert(T obj,IEqualityComparer? comparer=null); /// /// Добавление объекта в коллекцию на конкретную позицию /// /// Добавляемый объект /// Позиция /// true - вставка прошла удачно, false - вставка не удалась - bool Insert(T obj, int position); + bool Insert(T obj, int position, IEqualityComparer? comparer=null); /// /// Удаление объекта из коллекции с конкретной позиции /// @@ -50,4 +52,10 @@ public interface ICollectionGenericObjects /// /// IEnumerable GetItems(); + + /// + /// Сортировка коллекции + /// + /// + void CollectionSort(IComparer? comparer); } diff --git a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs index d8b97cb..91be125 100644 --- a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs +++ b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs @@ -1,9 +1,6 @@ -using AntiAircraftGun.Exceptions; -using System; -using System.Collections.Generic; +using AntiAircraftGun.Drawnings; +using AntiAircraftGun.Exceptions; using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace AntiAircraftGun.CollectionGenericObjects; /// @@ -37,21 +34,30 @@ public class ListGenericObjects : ICollectionGenericObjects // +- if (!_collection.Any()) { return null; } if (_collection.Count <= position || position < 0 || position >= _maxCount) { - throw new PostiionOutOfCollectionException(Count); + throw new PositionOutOfCollectionException(Count); } return _collection[position]; } - public bool Insert(T obj) + public bool Insert(T obj, IEqualityComparer comparer = null) { // TODO проверка, что не превышено максимальное количество элементов // TODO вставка в конец набора // TODO выброс ошибки, если переполнение // +- + + if (comparer != null) + { + if (_collection.Contains(obj,comparer)) + { + throw new ObjectIsEqualException(); + } + } + if (_collection.Count>=_maxCount) throw new CollectionOverflowExecption(_maxCount); _collection.Add(obj); return true; } - public bool Insert(T obj, int position) + public bool Insert(T obj, int position, IEqualityComparer comparer = null) { // TODO проверка, что не превышено максимальное количество элементов // TODO проверка позиции @@ -59,8 +65,16 @@ public class ListGenericObjects : ICollectionGenericObjects // TODO выброс ошибки, если выход за границу // TODO выброс ошибки, если переполнение // +- + + if (comparer != null) + { + if (_collection.Contains(obj, comparer)) + { + throw new ObjectIsEqualException(); + } + } if (Count>=_maxCount) throw new CollectionOverflowExecption(_maxCount); - if (position >= Count || position < 0) { throw new PostiionOutOfCollectionException(position); } + if (position >= Count || position < 0) { throw new PositionOutOfCollectionException(position); } _collection.Insert(position, obj); return true; } @@ -70,7 +84,7 @@ public class ListGenericObjects : ICollectionGenericObjects // TODO удаление объекта из списка // TODO выброс ошибки, если выход за границу массива // +- - if(position < 0 || position >= _maxCount) throw new PostiionOutOfCollectionException(position); + if(position < 0 || position >= _maxCount) throw new PositionOutOfCollectionException(position); if (_collection[position] == null) { return false; @@ -85,4 +99,9 @@ public class ListGenericObjects : ICollectionGenericObjects { for(int i=0; i<_collection.Count; i++) yield return _collection[i]; } + + void ICollectionGenericObjects.CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs index a701d5d..59e16a7 100644 --- a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -using AntiAircraftGun.Exceptions; +using AntiAircraftGun.Drawnings; +using AntiAircraftGun.Exceptions; using System.Data.Entity.Core; using System.Diagnostics; @@ -55,14 +56,23 @@ internal class MassiveGenericObjects : ICollectionGenericObjects } if (position >= _collection.Length || position<0) { - throw new PostiionOutOfCollectionException(position); + throw new PositionOutOfCollectionException(position); } return _collection[position]; } - public bool Insert(T obj) + public bool Insert(T obj, IEqualityComparer comparer = null) { // TODO вставка в свободное место набора // TODO выброс ошибки, если переполнение + + if (comparer != null) + { + foreach (T? item in _collection) + { + if ((comparer as IEqualityComparer).Equals(obj as DrawningGun, item as DrawningGun)) + throw new ObjectIsEqualException(); + } + } for (int i = 0; i < Count; i++) { if (InsertingElementCollection(i, obj)) return true; @@ -70,7 +80,7 @@ internal class MassiveGenericObjects : ICollectionGenericObjects throw new CollectionOverflowExecption(Count); } - public bool Insert(T obj, int position) + public bool Insert(T obj, int position, IEqualityComparer comparer = null) { // TODO проверка позиции // TODO проверка, что элемент массива по этой позиции пустой, если нет, то @@ -80,9 +90,19 @@ internal class MassiveGenericObjects : ICollectionGenericObjects // TODO выброс ошибки, если переполнение // TODO выброс ошибки, если выход за границу массива // +- - if(position>=_collection.Length||position<0) + + if (comparer != null) { - throw new PostiionOutOfCollectionException(position); + foreach (T? item in _collection) + { + if ((comparer as IEqualityComparer).Equals(obj as DrawningGun, item as DrawningGun)) + throw new ObjectIsEqualException(); + } + } + + if (position>=_collection.Length||position<0) + { + throw new PositionOutOfCollectionException(position); } if (InsertingElementCollection(position, obj)) return true; @@ -105,7 +125,7 @@ internal class MassiveGenericObjects : ICollectionGenericObjects // TODO выброс ошибки, если выход за границу // TODO выброс ошибки, если пустой // +- - if(position >= _collection.Length || position < 0) throw new PostiionOutOfCollectionException(position); + if(position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); if (_collection[position] == null) throw new Exceptions.ObjectNotFoundException(position); _collection[position] = null; return true; @@ -132,4 +152,9 @@ internal class MassiveGenericObjects : ICollectionGenericObjects { for (int i=0; i < _collection.Length; i++) yield return _collection[i]; } + + void ICollectionGenericObjects.CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } diff --git a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs index e7c29a2..cff5d27 100644 --- a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs +++ b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs @@ -13,11 +13,11 @@ where T : DrawningGun /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); private readonly string _collectionKey = "CollectionStorage"; @@ -28,7 +28,7 @@ where T : DrawningGun /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// /// Добавление коллекции в хранилище @@ -39,21 +39,13 @@ where T : DrawningGun { // TODO проверка, что name не пустой и нет в словаре записи с таким ключом // TODO Прописать логику для добавления - if (name.Length<=0 || _storages.ContainsKey(name)) - { - return; - } - switch(collectionType) - { - case CollectionType.List: - _storages.Add(name, new ListGenericObjects()); - break; - case CollectionType.Massive: - _storages.Add(name, new MassiveGenericObjects()); - break; - default: - return; - } + CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty); + if (_storages.ContainsKey(collectionInfo)) return; + if (collectionType == CollectionType.None) return; + else if (collectionType == CollectionType.Massive) + _storages[collectionInfo] = new MassiveGenericObjects(); + else if (collectionType == CollectionType.List) + _storages[collectionInfo] = new ListGenericObjects(); } /// /// Удаление коллекции @@ -62,8 +54,9 @@ where T : DrawningGun public void DelCollection(string name) { // TODO Прописать логику для удаления коллекции - if(!_storages.ContainsKey(name)) { return; } - _storages.Remove(name); + CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty); + if (!_storages.ContainsKey(collectionInfo)) { return; } + _storages.Remove(collectionInfo); } /// /// Доступ к коллекции @@ -75,8 +68,9 @@ where T : DrawningGun get { // TODO Продумать логику получения объекта - if (!_storages.ContainsKey(name)) { return null; } - return _storages[name]; + CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty); + if (!_storages.ContainsKey(collectionInfo)) { return null; } + return _storages[collectionInfo]; } } /// @@ -94,15 +88,13 @@ where T : DrawningGun StringBuilder sb = new(); sb.Append(_collectionKey); - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> value in _storages) { sb.Append(Environment.NewLine); // Не сохраняем пустые коллекции if (value.Value.Count == 0) continue; sb.Append(value.Key); sb.Append(_separatorForKeyValue); - sb.Append(value.Value.GetCollectionType); - sb.Append(_separatorForKeyValue); sb.Append(value.Value.MaxCount); sb.Append(_separatorForKeyValue); foreach (T? item in value.Value.GetItems()) @@ -145,18 +137,20 @@ where T : DrawningGun while ((strs = reader.ReadLine()) != null) { string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + if (record.Length != 3) { continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new Exception("Не удалось определить информацию коллекции: " + record[0]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? + throw new Exception("Не удалось создать коллекцию"); if (collection == null) { throw new Exception("Не удалось создать коллекцию"); } - collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + collection.MaxCount = Convert.ToInt32(record[1]); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { if (elem?.CreateDrawningCun() is T gun) @@ -174,7 +168,7 @@ where T : DrawningGun } } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } } diff --git a/AntiAircraftGun/AntiAircraftGun/Drawnings/DrawningGunCompareByColor.cs b/AntiAircraftGun/AntiAircraftGun/Drawnings/DrawningGunCompareByColor.cs new file mode 100644 index 0000000..3e22e0a --- /dev/null +++ b/AntiAircraftGun/AntiAircraftGun/Drawnings/DrawningGunCompareByColor.cs @@ -0,0 +1,28 @@ +namespace AntiAircraftGun.Drawnings; + +public class DrawningGunCompareByColor : IComparer +{ + public int Compare(DrawningGun? x, DrawningGun? y) + { + if (x == null || x.EntityGun == null) + { + return 1; + } + + if (y == null || y.EntityGun == null) + { + return -1; + } + var bodycolorCompare = x.EntityGun.BodyColor.Name.CompareTo(y.EntityGun.BodyColor.Name); + if (bodycolorCompare != 0) + { + return bodycolorCompare; + } + var speedCompare = x.EntityGun.Speed.CompareTo(y.EntityGun.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityGun.Weight.CompareTo(y.EntityGun.Weight); + } +} diff --git a/AntiAircraftGun/AntiAircraftGun/Drawnings/DrawningGunCompareByType.cs b/AntiAircraftGun/AntiAircraftGun/Drawnings/DrawningGunCompareByType.cs new file mode 100644 index 0000000..fd5f041 --- /dev/null +++ b/AntiAircraftGun/AntiAircraftGun/Drawnings/DrawningGunCompareByType.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AntiAircraftGun.Drawnings; + +/// +/// Сравнение по типу, скорости, весу +/// +public class DrawningGunCompareByType : IComparer +{ + public int Compare(DrawningGun? x, DrawningGun? y) + { + if (x == null || x.EntityGun == null) + { + return -1; + } + if (y == null || y.EntityGun == null) + { + return 1; + } + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + var speedCompare = x.EntityGun.Speed.CompareTo(y.EntityGun.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityGun.Weight.CompareTo(y.EntityGun.Weight); + } +} diff --git a/AntiAircraftGun/AntiAircraftGun/Drawnings/DrawningGunEqutables.cs b/AntiAircraftGun/AntiAircraftGun/Drawnings/DrawningGunEqutables.cs new file mode 100644 index 0000000..5c2e955 --- /dev/null +++ b/AntiAircraftGun/AntiAircraftGun/Drawnings/DrawningGunEqutables.cs @@ -0,0 +1,64 @@ + +using AntiAircraftGun.Entities; +using System.Diagnostics.CodeAnalysis; + +namespace AntiAircraftGun.Drawnings; + +/// +/// Реализатор сравнения двух объектов +/// +public class DrawningGunEqutables : IEqualityComparer +{ + public bool Equals(DrawningGun? x, DrawningGun? y) + { + if (x == null || x.EntityGun == null) + { + return false; + } + if (y == null || y.EntityGun == null) + { + return false; + } + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + if (x.EntityGun.Speed != y.EntityGun.Speed) + { + return false; + } + if (x.EntityGun.Weight != y.EntityGun.Weight) + { + return false; + } + if (x.EntityGun.BodyColor != y.EntityGun.BodyColor) + { + return false; + } + if (x is DrawningAntiAircraftGun && y is DrawningAntiAircraftGun) + { + // TODO доделать логику сравнения дополнительных параметров + + EntityAntiAircraftGun left = (EntityAntiAircraftGun)x.EntityGun; + EntityAntiAircraftGun right=(EntityAntiAircraftGun)y.EntityGun; + if(left.OptionalElementsColor != right.OptionalElementsColor) + { + return false; + } + if(left.Radar != right.Radar) + { + return false; + } + if(left.Hatch != right.Hatch) + { + return false; + } + } + return true; + } + + public int GetHashCode([DisallowNull] DrawningGun? obj) + { + return obj.GetHashCode(); + } +} diff --git a/AntiAircraftGun/AntiAircraftGun/Exceptions/ObjectIsEqualException.cs b/AntiAircraftGun/AntiAircraftGun/Exceptions/ObjectIsEqualException.cs new file mode 100644 index 0000000..d64b6f0 --- /dev/null +++ b/AntiAircraftGun/AntiAircraftGun/Exceptions/ObjectIsEqualException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace AntiAircraftGun.Exceptions; + +/// +/// Ошибка переполнения +/// +[Serializable] +public class ObjectIsEqualException:ApplicationException +{ + public ObjectIsEqualException(int count) : base("В коллекции содержится равный элемент: " + count) { } + public ObjectIsEqualException() : base() { } + public ObjectIsEqualException(string message) : base(message) { } + public ObjectIsEqualException(string message, Exception exception) : base(message, exception) { } + protected ObjectIsEqualException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} diff --git a/AntiAircraftGun/AntiAircraftGun/Exceptions/PostiionOutOfCollectionException.cs b/AntiAircraftGun/AntiAircraftGun/Exceptions/PositionOutOfCollectionException.cs similarity index 51% rename from AntiAircraftGun/AntiAircraftGun/Exceptions/PostiionOutOfCollectionException.cs rename to AntiAircraftGun/AntiAircraftGun/Exceptions/PositionOutOfCollectionException.cs index e40c04c..c596c99 100644 --- a/AntiAircraftGun/AntiAircraftGun/Exceptions/PostiionOutOfCollectionException.cs +++ b/AntiAircraftGun/AntiAircraftGun/Exceptions/PositionOutOfCollectionException.cs @@ -7,11 +7,11 @@ using System.Threading.Tasks; namespace AntiAircraftGun.Exceptions; -public class PostiionOutOfCollectionException:ApplicationException +public class PositionOutOfCollectionException:ApplicationException { - public PostiionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { } - public PostiionOutOfCollectionException() : base() { } - public PostiionOutOfCollectionException(string message) : base(message) { } - public PostiionOutOfCollectionException(string message, Exception innerException) : base(message, innerException) { } - protected PostiionOutOfCollectionException(SerializationInfo info, StreamingContext context) : base(info, context) { } + public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { } + public PositionOutOfCollectionException() : base() { } + public PositionOutOfCollectionException(string message) : base(message) { } + public PositionOutOfCollectionException(string message, Exception innerException) : base(message, innerException) { } + protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext context) : base(info, context) { } } diff --git a/AntiAircraftGun/AntiAircraftGun/FormGunCollections.Designer.cs b/AntiAircraftGun/AntiAircraftGun/FormGunCollections.Designer.cs index cbbee88..dd37a2c 100644 --- a/AntiAircraftGun/AntiAircraftGun/FormGunCollections.Designer.cs +++ b/AntiAircraftGun/AntiAircraftGun/FormGunCollections.Designer.cs @@ -52,6 +52,8 @@ downloadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + buttonSortByColor = new Button(); + buttonSortByType = new Button(); groupBox1.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); @@ -64,15 +66,17 @@ groupBox1.Controls.Add(panelCompanyTools); groupBox1.Controls.Add(panelStorage); groupBox1.Dock = DockStyle.Right; - groupBox1.Location = new Point(981, 28); + groupBox1.Location = new Point(1011, 28); groupBox1.Name = "groupBox1"; - groupBox1.Size = new Size(235, 744); + groupBox1.Size = new Size(235, 855); groupBox1.TabIndex = 0; groupBox1.TabStop = false; groupBox1.Text = "Инструменты"; // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonCreateCompany); panelCompanyTools.Controls.Add(comboBoxSelectorCompany); panelCompanyTools.Controls.Add(buttonAddGun); @@ -81,9 +85,9 @@ panelCompanyTools.Controls.Add(maskedTextBox); panelCompanyTools.Controls.Add(buttonRemoveGun); panelCompanyTools.Dock = DockStyle.Bottom; - panelCompanyTools.Location = new Point(3, 384); + panelCompanyTools.Location = new Point(3, 395); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(229, 357); + panelCompanyTools.Size = new Size(229, 457); panelCompanyTools.TabIndex = 9; // // buttonCreateCompany @@ -248,7 +252,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 28); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(981, 744); + pictureBox.Size = new Size(1011, 855); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -258,7 +262,7 @@ menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; - menuStrip.Size = new Size(1216, 28); + menuStrip.Size = new Size(1246, 28); menuStrip.TabIndex = 2; menuStrip.Text = "menuStrip1"; // @@ -293,11 +297,33 @@ // openFileDialog.Filter = "txt files|*.txt"; // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByColor.Location = new Point(9, 397); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(214, 39); + buttonSortByColor.TabIndex = 10; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += buttonSortByColor_Click; + // + // buttonSortByType + // + buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByType.Location = new Point(9, 358); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(214, 33); + buttonSortByType.TabIndex = 9; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += buttonSortByType_Click; + // // FormGunCollections // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1216, 772); + ClientSize = new Size(1246, 883); Controls.Add(pictureBox); Controls.Add(groupBox1); Controls.Add(menuStrip); @@ -342,5 +368,7 @@ private ToolStripMenuItem downloadToolStripMenuItem; private SaveFileDialog saveFileDialog; private OpenFileDialog openFileDialog; + private Button buttonSortByColor; + private Button buttonSortByType; } } \ No newline at end of file diff --git a/AntiAircraftGun/AntiAircraftGun/FormGunCollections.cs b/AntiAircraftGun/AntiAircraftGun/FormGunCollections.cs index 2b7884e..b0ed98a 100644 --- a/AntiAircraftGun/AntiAircraftGun/FormGunCollections.cs +++ b/AntiAircraftGun/AntiAircraftGun/FormGunCollections.cs @@ -262,7 +262,7 @@ listBoxCollection.SelectedItem == null) listBoxCollection.Items.Clear(); for (int i = 0; i < _storageCollection.Keys?.Count; ++i) { - string? colName = _storageCollection.Keys?[i]; + string? colName = _storageCollection.Keys?[i].Name; if (!string.IsNullOrEmpty(colName)) { listBoxCollection.Items.Add(colName); @@ -316,4 +316,35 @@ listBoxCollection.SelectedItem == null) } } } + + /// + /// Сортировка по типу + /// + /// + /// + private void buttonSortByType_Click(object sender, EventArgs e) + { + CompareGun(new DrawningGunCompareByType()); + } + + /// + /// Сортировка по цвету + /// + /// + /// + private void buttonSortByColor_Click(object sender, EventArgs e) + { + CompareGun(new DrawningGunCompareByColor()); + } + + /// + /// Сортировка по сравнителю + /// + /// + private void CompareGun(IComparer comparer) + { + if (comparer == null) return; + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } } -- 2.25.1 From 85c0cbdaba81a804a84447db0571327326a8f276 Mon Sep 17 00:00:00 2001 From: Ctepa Date: Mon, 20 May 2024 14:27:40 +0300 Subject: [PATCH 2/2] =?UTF-8?q?=D0=9F=D1=80=D0=B8=D0=BD=D1=8F=D1=82=D0=B0?= =?UTF-8?q?=D1=8F=208=20=D0=BB=D0=B0=D0=B1=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ICollectionGenericObjects.cs | 4 +-- .../ListGenericObjects.cs | 23 ++++++++++----- .../MassiveGenericObjects.cs | 4 +-- .../StorageCollection.cs | 4 +-- .../Drawnings/DrawningGunEqutables.cs | 28 +++++++++---------- .../AntiAircraftGun/FormGunCollections.cs | 7 ++++- 6 files changed, 42 insertions(+), 28 deletions(-) diff --git a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/ICollectionGenericObjects.cs b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/ICollectionGenericObjects.cs index 16af12a..fbb180c 100644 --- a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -23,14 +23,14 @@ public interface ICollectionGenericObjects /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась - bool Insert(T obj,IEqualityComparer? comparer=null); + bool Insert(T obj,IEqualityComparer? comparer=null); /// /// Добавление объекта в коллекцию на конкретную позицию /// /// Добавляемый объект /// Позиция /// true - вставка прошла удачно, false - вставка не удалась - bool Insert(T obj, int position, IEqualityComparer? comparer=null); + bool Insert(T obj, int position, IEqualityComparer? comparer=null); /// /// Удаление объекта из коллекции с конкретной позиции /// diff --git a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs index 91be125..f9927d9 100644 --- a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs +++ b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs @@ -1,6 +1,5 @@ using AntiAircraftGun.Drawnings; using AntiAircraftGun.Exceptions; -using System.Linq; namespace AntiAircraftGun.CollectionGenericObjects; /// @@ -38,7 +37,7 @@ public class ListGenericObjects : ICollectionGenericObjects } return _collection[position]; } - public bool Insert(T obj, IEqualityComparer comparer = null) + public bool Insert(T obj, IEqualityComparer comparer = null) { // TODO проверка, что не превышено максимальное количество элементов // TODO вставка в конец набора @@ -47,9 +46,14 @@ public class ListGenericObjects : ICollectionGenericObjects if (comparer != null) { - if (_collection.Contains(obj,comparer)) + foreach (T? item in _collection) { - throw new ObjectIsEqualException(); + if (item == null) continue; + if ((comparer as IEqualityComparer).Equals(obj as DrawningGun, item as DrawningGun)) + { + + throw new ObjectIsEqualException(); + } } } @@ -57,7 +61,7 @@ public class ListGenericObjects : ICollectionGenericObjects _collection.Add(obj); return true; } - public bool Insert(T obj, int position, IEqualityComparer comparer = null) + public bool Insert(T obj, int position, IEqualityComparer comparer = null) { // TODO проверка, что не превышено максимальное количество элементов // TODO проверка позиции @@ -68,9 +72,14 @@ public class ListGenericObjects : ICollectionGenericObjects if (comparer != null) { - if (_collection.Contains(obj, comparer)) + foreach (T? item in _collection) { - throw new ObjectIsEqualException(); + if (item == null) continue; + if ((comparer as IEqualityComparer).Equals(obj as DrawningGun, item as DrawningGun)) + { + + throw new ObjectIsEqualException(); + } } } if (Count>=_maxCount) throw new CollectionOverflowExecption(_maxCount); diff --git a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs index 59e16a7..73a1aee 100644 --- a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs @@ -60,7 +60,7 @@ internal class MassiveGenericObjects : ICollectionGenericObjects } return _collection[position]; } - public bool Insert(T obj, IEqualityComparer comparer = null) + public bool Insert(T obj, IEqualityComparer comparer = null) { // TODO вставка в свободное место набора // TODO выброс ошибки, если переполнение @@ -80,7 +80,7 @@ internal class MassiveGenericObjects : ICollectionGenericObjects throw new CollectionOverflowExecption(Count); } - public bool Insert(T obj, int position, IEqualityComparer comparer = null) + public bool Insert(T obj, int position, IEqualityComparer comparer = null) { // TODO проверка позиции // TODO проверка, что элемент массива по этой позиции пустой, если нет, то diff --git a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs index cff5d27..6baf052 100644 --- a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs +++ b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs @@ -159,12 +159,12 @@ where T : DrawningGun { if (!collection.Insert(gun)) { - throw new Exception("Объект не удалось добавить в коллекию: " + record[3]); + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); } } catch (CollectionOverflowExecption ex) { - throw new Exception("Коллекция переполнена",ex); + throw new Exception("Коллекция переполнена", ex); } } } diff --git a/AntiAircraftGun/AntiAircraftGun/Drawnings/DrawningGunEqutables.cs b/AntiAircraftGun/AntiAircraftGun/Drawnings/DrawningGunEqutables.cs index 5c2e955..9d0443a 100644 --- a/AntiAircraftGun/AntiAircraftGun/Drawnings/DrawningGunEqutables.cs +++ b/AntiAircraftGun/AntiAircraftGun/Drawnings/DrawningGunEqutables.cs @@ -35,23 +35,23 @@ public class DrawningGunEqutables : IEqualityComparer { return false; } - if (x is DrawningAntiAircraftGun && y is DrawningAntiAircraftGun) + if (x is DrawningAntiAircraftGun xa && y is DrawningAntiAircraftGun ya ) { // TODO доделать логику сравнения дополнительных параметров - - EntityAntiAircraftGun left = (EntityAntiAircraftGun)x.EntityGun; - EntityAntiAircraftGun right=(EntityAntiAircraftGun)y.EntityGun; - if(left.OptionalElementsColor != right.OptionalElementsColor) + if(xa.EntityGun is EntityAntiAircraftGun left && ya.EntityGun is EntityAntiAircraftGun right) { - return false; - } - if(left.Radar != right.Radar) - { - return false; - } - if(left.Hatch != right.Hatch) - { - return false; + if (left.OptionalElementsColor != right.OptionalElementsColor) + { + return false; + } + if (left.Radar != right.Radar) + { + return false; + } + if (left.Hatch != right.Hatch) + { + return false; + } } } return true; diff --git a/AntiAircraftGun/AntiAircraftGun/FormGunCollections.cs b/AntiAircraftGun/AntiAircraftGun/FormGunCollections.cs index b0ed98a..d448036 100644 --- a/AntiAircraftGun/AntiAircraftGun/FormGunCollections.cs +++ b/AntiAircraftGun/AntiAircraftGun/FormGunCollections.cs @@ -54,7 +54,7 @@ public partial class FormGunCollections : Form /// Добавление автомобиля в коллекцию /// /// - private void SetGun(DrawningGun gun) + private void SetGun(DrawningGun? gun) { try { @@ -72,6 +72,11 @@ public partial class FormGunCollections : Form MessageBox.Show("Не удалось добавить объект"); _logger.LogError("Ошибка: {Message}", ex.Message); } + catch (ObjectIsEqualException ex) + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); + } } /// -- 2.25.1