8 лабораторная работа

This commit is contained in:
Anastasia_52 2024-06-13 22:26:39 +04:00
parent 9790d72de2
commit 4de7934c88
12 changed files with 484 additions and 114 deletions

View File

@ -63,7 +63,7 @@ public abstract class AbstractCompany
/// <returns></returns> /// <returns></returns>
public static int operator +(AbstractCompany company, DrawingWarship warship) public static int operator +(AbstractCompany company, DrawingWarship warship)
{ {
return company._collection.Insert(warship); return company._collection.Insert(warship, new DrawingWarshipEqutables());
} }
/// <summary> /// <summary>
/// Перезагрузка оператора удаления для класса /// Перезагрузка оператора удаления для класса
@ -105,6 +105,12 @@ public abstract class AbstractCompany
return bitmap; return bitmap;
} }
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<DrawingWarship?> comparer) => _collection?.CollectionSort(comparer);
/// <summary> /// <summary>
/// Вывод заднего фона /// Вывод заднего фона
/// </summary> /// </summary>

View File

@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectLinkor.CollectionGenericObjects;
/// <summary>
/// Класс, хранящий информацию по коллекции
/// </summary>
public class CollectionInfo : IEquatable<CollectionInfo>
{
/// <summary>
/// Название
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Тип
/// </summary>
public CollectionType CollectionType { get; private set; }
/// <summary>
/// Описние
/// </summary>
public string Description { get; private set; }
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separator = "-";
/// <summary>
/// Конструктор
/// </summary>
/// <param name="name"></param>
/// <param name="collectionType"></param>
/// <param name="description"></param>
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();
}
}

View File

@ -22,16 +22,18 @@ public interface ICollectionGenericObjects<T>
/// Добавление объекта в коллекцию /// Добавление объекта в коллекцию
/// </summary> /// </summary>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <param name="comparer">Сравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj); int Insert(T obj, IEqualityComparer<T?> comparer = null);
/// <summary> /// <summary>
/// Добавление объекта в коллекцию на конкретную позицию /// Добавление объекта в коллекцию на конкретную позицию
/// </summary> /// </summary>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <param name="comparer">Сравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position); int Insert(T obj, int position, IEqualityComparer<T?> comparer = null);
/// <summary> /// <summary>
/// Удаление объекта из коллекции с конкретной позиции /// Удаление объекта из коллекции с конкретной позиции
@ -57,4 +59,10 @@ public interface ICollectionGenericObjects<T>
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
IEnumerable<T> GetItems(); IEnumerable<T> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer"></param>
void CollectionSort(IComparer<T?> comparer);
} }

View File

@ -54,41 +54,41 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{ {
// проверка, что не превышено максимальное количество элементов if (comparer != null)
if (_collection.Count >= _maxCount)
{ {
throw new CollectionOverflowException(_maxCount); if (_collection.Contains(obj, comparer))
{
throw new ObjectIsEqualException();
}
} }
// вставка в конец набора if (Count == _maxCount) throw new CollectionOverflowException();
_collection.Add(obj); _collection.Add(obj);
return _maxCount; return Count;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{ {
// проверка, что не превышено максимальное количество элементов if (comparer != null)
if (Count >= _maxCount) {
throw new CollectionOverflowException(_maxCount); if (_collection.Contains(obj, comparer))
{
// проверка позиции throw new ObjectIsEqualException();
if (position < 0 || position >= _maxCount) }
throw new PositionOutOfCollectionException(position); }
if (Count == _maxCount) throw new CollectionOverflowException(Count);
// вставка по позиции if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
} }
public T Remove(int position) public T Remove(int position)
{ {
// проверка позиции if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (position < 0 || position > _maxCount) throw new PositionOutOfCollectionException(position); T obj = _collection[position];
// удаление объекта из списка _collection.RemoveAt(position);
T temp = _collection[position]; return obj;
_collection[position] = null;
return temp;
} }
public IEnumerable<T> GetItems() public IEnumerable<T> GetItems()
@ -98,4 +98,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
} }

View File

@ -1,4 +1,5 @@
using ProjectLinkor.CollectionGenericObjects; using ProjectLinkor.CollectionGenericObjects;
using ProjectLinkor.Drawnings;
using ProjectLinkor.Exceptions; using ProjectLinkor.Exceptions;
namespace ProjectLinkor.CollectionGenericObjects; namespace ProjectLinkor.CollectionGenericObjects;
@ -59,9 +60,16 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{ {
// TODO вставка в свободное место набора if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawingWarship>).Equals(obj as DrawingWarship, item as DrawingWarship))
throw new ObjectIsEqualException();
}
}
int index = 0; int index = 0;
while (index < _collection.Length) while (index < _collection.Length)
{ {
@ -70,64 +78,61 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
_collection[index] = obj; _collection[index] = obj;
return index; return index;
} }
index++; index++;
} }
throw new CollectionOverflowException(Count); throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{ {
// проверка позиции if (comparer != null)
if (position >= _collection.Length || position < 0)
throw new PositionOutOfCollectionException(position);
// проверка, что элемент массива по этой позиции пустой, если нет, то
if (_collection[position] != null)
{ {
// проверка, что после вставляемого элемента в массиве есть пустой элемент foreach (T? item in _collection)
int nullIndex = -1;
for (int i = position + 1; i < Count; i++)
{ {
if (_collection[i] == null) if ((comparer as IEqualityComparer<DrawingWarship>).Equals(obj as DrawingWarship, item as DrawingWarship))
{ throw new ObjectIsEqualException();
nullIndex = i;
break;
}
} }
// Если пустого элемента нет, то выходим
if (nullIndex < 0)
{
return -1;
}
// сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента
int j = nullIndex - 1;
while (j >= position)
{
_collection[j + 1] = _collection[j];
j--;
}
throw new CollectionOverflowException(Count);
} }
// вставка по позиции if (position >= _collection.Length || position < 0)
_collection[position] = obj; {
return position; throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
_collection[position] = obj;
return position;
}
int index;
for (index = position + 1; index < _collection.Length; ++index)
{
if (_collection[index] == null)
{
_collection[position] = obj;
return position;
}
}
for (index = position - 1; index >= 0; --index)
{
if (_collection[index] == null)
{
_collection[position] = obj;
return position;
}
}
throw new CollectionOverflowException(Count);
} }
public T? Remove(int position) public T? Remove(int position)
{ {
// проверка позиции if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
// удаление объекта из массива, присвоив элементу массива значение null if (_collection[position] == null) throw new ObjectNotFoundException(position);
if (position >= _collection.Length || position < 0) T obj = _collection[position];
{
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
throw new ObjectNotFoundException(position);
}
T temp = _collection[position];
_collection[position] = null; _collection[position] = null;
return temp; return obj;
} }
public IEnumerable<T> GetItems() public IEnumerable<T> GetItems()
@ -137,4 +142,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
} }

View File

@ -1,5 +1,6 @@
using ProjectLinkor.Drawnings; using ProjectLinkor.Drawnings;
using ProjectLinkor.Exceptions; using ProjectLinkor.Exceptions;
using System.Collections.Generic;
using System.Text; using System.Text;
namespace ProjectLinkor.CollectionGenericObjects; namespace ProjectLinkor.CollectionGenericObjects;
@ -14,27 +15,36 @@ public class StorageCollection<T>
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
private Dictionary<string, ICollectionGenericObjects<T>> _storages; readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary> /// <summary>
/// Возвращение списка названий коллекции /// Возвращение списка названий коллекции
/// </summary> /// </summary>
public List<string> Keys => _storages.Keys.ToList(); public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
} }
private readonly string _collectionKey = "CollectionsStorage";
private readonly string _separatorForKeyValue = "|";
private readonly string _separatorItems = ";";
/// <summary> /// <summary>
/// Добавление коллекции в хранилище /// Добавление коллекции в хранилище
/// </summary> /// </summary>
@ -42,18 +52,20 @@ public class StorageCollection<T>
/// <param name="collectionType">Тип коллекции</param> /// <param name="collectionType">Тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(string name, CollectionType collectionType)
{ {
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name)) // проверка, что name не пустой и нет в словаре записи с таким ключом
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(new CollectionInfo(name, collectionType, string.Empty)))
{ {
MessageBox.Show("Коллекция с таким именем уже существует", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
// TODO Прописать логику для добавления // прописать логику для добавления
if (collectionType == CollectionType.List) if (collectionType == CollectionType.List)
{ {
_storages.Add(name, new ListGenericObjects<T>()); _storages.Add(new CollectionInfo(name, collectionType, string.Empty), new ListGenericObjects<T>());
} }
if (collectionType == CollectionType.Massive) if (collectionType == CollectionType.Massive)
{ {
_storages.Add(name, new MassiveGenericObjects<T>()); _storages.Add(new CollectionInfo(name, collectionType, string.Empty), new MassiveGenericObjects<T>());
} }
} }
@ -63,10 +75,9 @@ public class StorageCollection<T>
/// <param name="name"></param> /// <param name="name"></param>
public void DelCollection(string name) public void DelCollection(string name)
{ {
// TODO Прописать логику для удаления коллекции // прописать логику для удаления коллекции
if (!_storages.ContainsKey(name)) if (!_storages.ContainsKey(new CollectionInfo(name, CollectionType.None, string.Empty))) return;
return; _storages.Remove(new CollectionInfo(name, CollectionType.None, string.Empty));
_storages.Remove(name);
} }
/// <summary> /// <summary>
@ -78,10 +89,10 @@ public class StorageCollection<T>
{ {
get get
{ {
// TODO Продумать логику получения объекта // продумать логику получения объекта
if (_storages.ContainsKey((string)name)) if (_storages.ContainsKey(new CollectionInfo(name, CollectionType.None, string.Empty)))
{ {
return _storages[name]; return _storages[new CollectionInfo(name, CollectionType.None, string.Empty)];
} }
return null; return null;
} }
@ -107,7 +118,7 @@ public class StorageCollection<T>
using (StreamWriter writer = new StreamWriter(filename)) using (StreamWriter writer = new StreamWriter(filename))
{ {
writer.Write(_collectionKey); writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages) foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{ {
writer.Write(Environment.NewLine); writer.Write(Environment.NewLine);
// не сохраняем пустые коллекции // не сохраняем пустые коллекции
@ -118,8 +129,6 @@ public class StorageCollection<T>
writer.Write(value.Key); writer.Write(value.Key);
writer.Write(_separatorForKeyValue); writer.Write(_separatorForKeyValue);
writer.Write(value.Value.GetCollectionType);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.MaxCount); writer.Write(value.Value.MaxCount);
writer.Write(_separatorForKeyValue); writer.Write(_separatorForKeyValue);
@ -161,7 +170,6 @@ public class StorageCollection<T>
if (!str.StartsWith(_collectionKey)) if (!str.StartsWith(_collectionKey))
{ {
//если нет такой записи, то это не те данные
throw new Exception("В файле неверные данные"); throw new Exception("В файле неверные данные");
} }
@ -170,21 +178,23 @@ public class StorageCollection<T>
while ((strs = reader.ReadLine()) != null) while ((strs = reader.ReadLine()) != null)
{ {
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4) if (record.Length != 3)
{ {
continue; continue;
} }
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); throw new Exception("Не удалось определить информацию коллекции" + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось создать коллекцию");
if (collection == null) if (collection == null)
{ {
throw new Exception("Не удалось создать коллекцию"); throw new Exception("Не удалось создать коллекцию");
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawingWarship() is T bulldozer) if (elem?.CreateDrawingWarship() is T bulldozer)
@ -203,7 +213,7 @@ public class StorageCollection<T>
} }
} }
_storages.Add(record[0], collection); _storages.Add(collectionInfo, collection);
} }
} }
} }

View File

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectLinkor.Drawnings;
/// <summary>
/// Сравнение по типу, скорости, весу
/// </summary>
internal class DrawingWarshipCompareByType : IComparer<DrawingWarship?>
{
public int Compare(DrawingWarship? x, DrawingWarship? y)
{
if (x == null || x.EntityWarship == null)
{
return 1;
}
if (y == null || y.EntityWarship == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityWarship.Speed.CompareTo(y.EntityWarship.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityWarship.Weight.CompareTo(y.EntityWarship.Weight);
}
}

View File

@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectLinkor.Drawnings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawingWarshipComparerByColor : IComparer<DrawingWarship?>
{
public int Compare(DrawingWarship? x, DrawingWarship? y)
{
// TODO прописать логику сравнения по цветам, скорости, весу
if (x == null || x.EntityWarship == null)
{
return 1;
}
if (y == null || y.EntityWarship == null)
{
return -1;
}
if (x.EntityWarship.BodyColor != y.EntityWarship.BodyColor)
{
return x.EntityWarship.BodyColor.Name.CompareTo(y.EntityWarship.BodyColor.Name);
}
var speedCompare = x.EntityWarship.Speed.CompareTo(y.EntityWarship.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityWarship.Weight.CompareTo(y.EntityWarship.Weight);
}
}

View File

@ -0,0 +1,71 @@
using ProjectLinkor.Entities;
using System.Diagnostics.CodeAnalysis;
namespace ProjectLinkor.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawingWarshipEqutables : IEqualityComparer<DrawingWarship?>
{
public bool Equals(DrawingWarship? x, DrawingWarship? y)
{
if (x == null || x.EntityWarship == null)
{
return false;
}
if (y == null || y.EntityWarship == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityWarship.Speed != y.EntityWarship.Speed)
{
return false;
}
if (x.EntityWarship.Weight != y.EntityWarship.Weight)
{
return false;
}
if (x.EntityWarship.BodyColor != y.EntityWarship.BodyColor)
{
return false;
}
if (x is DrawningLinkor && y is DrawningLinkor)
{
// TODO доделать логику сравнения дополнительных параметров
EntityLinkor xLinkor = (EntityLinkor)x.EntityWarship;
EntityLinkor yLinkor = (EntityLinkor)y.EntityWarship;
if (xLinkor.AdditionalColor != yLinkor.AdditionalColor)
{
return false;
}
if (xLinkor.Сompartment != yLinkor.Сompartment)
{
return false;
}
if (xLinkor.GunTurret != yLinkor.GunTurret)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawingWarship obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ProjectLinkor.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[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) { }
}

View File

@ -52,6 +52,8 @@
loadToolStripMenuItem = new ToolStripMenuItem(); loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog(); saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog(); openFileDialog = new OpenFileDialog();
buttonSortByType = new Button();
buttonSortByColor = new Button();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
@ -75,6 +77,8 @@
// //
// panelCompanyTools // panelCompanyTools
// //
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddWarship); panelCompanyTools.Controls.Add(buttonAddWarship);
panelCompanyTools.Controls.Add(maskedTextBox1); panelCompanyTools.Controls.Add(maskedTextBox1);
panelCompanyTools.Controls.Add(buttonRemoveWarship); panelCompanyTools.Controls.Add(buttonRemoveWarship);
@ -82,15 +86,15 @@
panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 384); panelCompanyTools.Location = new Point(3, 374);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(286, 291); panelCompanyTools.Size = new Size(286, 301);
panelCompanyTools.TabIndex = 9; panelCompanyTools.TabIndex = 9;
// //
// buttonAddWarship // buttonAddWarship
// //
buttonAddWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonAddWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddWarship.Location = new Point(3, 16); buttonAddWarship.Location = new Point(3, 3);
buttonAddWarship.Name = "buttonAddWarship"; buttonAddWarship.Name = "buttonAddWarship";
buttonAddWarship.Size = new Size(271, 33); buttonAddWarship.Size = new Size(271, 33);
buttonAddWarship.TabIndex = 1; buttonAddWarship.TabIndex = 1;
@ -101,7 +105,7 @@
// maskedTextBox1 // maskedTextBox1
// //
maskedTextBox1.Anchor = AnchorStyles.Left | AnchorStyles.Right; maskedTextBox1.Anchor = AnchorStyles.Left | AnchorStyles.Right;
maskedTextBox1.Location = new Point(3, 81); maskedTextBox1.Location = new Point(3, 42);
maskedTextBox1.Mask = "00"; maskedTextBox1.Mask = "00";
maskedTextBox1.Name = "maskedTextBox1"; maskedTextBox1.Name = "maskedTextBox1";
maskedTextBox1.Size = new Size(271, 27); maskedTextBox1.Size = new Size(271, 27);
@ -110,7 +114,7 @@
// buttonRemoveWarship // buttonRemoveWarship
// //
buttonRemoveWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRemoveWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveWarship.Location = new Point(3, 124); buttonRemoveWarship.Location = new Point(3, 75);
buttonRemoveWarship.Name = "buttonRemoveWarship"; buttonRemoveWarship.Name = "buttonRemoveWarship";
buttonRemoveWarship.Size = new Size(271, 42); buttonRemoveWarship.Size = new Size(271, 42);
buttonRemoveWarship.TabIndex = 4; buttonRemoveWarship.TabIndex = 4;
@ -121,7 +125,7 @@
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(3, 220); buttonRefresh.Location = new Point(3, 171);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(271, 30); buttonRefresh.Size = new Size(271, 30);
buttonRefresh.TabIndex = 6; buttonRefresh.TabIndex = 6;
@ -132,7 +136,7 @@
// buttonGoToCheck // buttonGoToCheck
// //
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 172); buttonGoToCheck.Location = new Point(3, 123);
buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(271, 42); buttonGoToCheck.Size = new Size(271, 42);
buttonGoToCheck.TabIndex = 5; buttonGoToCheck.TabIndex = 5;
@ -294,6 +298,28 @@
// //
openFileDialog.Filter = "txt file | *.txt"; openFileDialog.Filter = "txt file | *.txt";
// //
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(3, 207);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(271, 42);
buttonSortByType.TabIndex = 8;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(3, 255);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(271, 30);
buttonSortByColor.TabIndex = 9;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// FormWarshipCollection // FormWarshipCollection
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(8F, 20F);
@ -342,5 +368,7 @@
private ToolStripMenuItem loadToolStripMenuItem; private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
} }
} }

View File

@ -105,22 +105,33 @@ public partial class FormWarshipCollection : Form
/// <param name="warship"></param> /// <param name="warship"></param>
private void SetWarship(DrawingWarship warship) private void SetWarship(DrawingWarship warship)
{ {
if (_company == null || warship == null)
{
return;
}
try try
{ {
if (_company == null || warship == null)
{
return;
}
if (_company + warship != -1) if (_company + warship != -1)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: {object}", warship.GetDataForSave()); _logger.LogInformation("Добавлен объект: " + warship.GetDataForSave());
} }
} }
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex) catch (CollectionOverflowException ex)
{ {
MessageBox.Show(ex.Message); MessageBox.Show("Не удалось добавить объект1");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show("Выход за границы коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ObjectIsEqualException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message); _logger.LogError("Ошибка: {Message}", ex.Message);
} }
@ -242,7 +253,7 @@ public partial class FormWarshipCollection : Form
listBoxCollection.Items.Clear(); listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i) for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{ {
string? colName = _storageCollection.Keys?[i]; string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName)) if (!string.IsNullOrEmpty(colName))
{ {
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(colName);
@ -329,4 +340,51 @@ public partial class FormWarshipCollection : Form
} }
} }
} }
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareWarship(new DrawingWarshipCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareExcavators(new DrawingWarshipComparerByColor());
}
private void CompareExcavators(IComparer<DrawingWarship?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareWarship(IComparer<DrawingWarship?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
} }