PIbd-12 ZagidulinGA Lab08 Simple #10

Closed
Grigorii_Zagidulin wants to merge 1 commits from Lab08 into Lab07
12 changed files with 409 additions and 69 deletions

View File

@ -58,9 +58,13 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningShip ship)
{
return company._collection.Insert(ship);
return company._collection.Insert(ship, new DrawningShipEqutables());
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningShip?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Перегрузка оператора удаления для класса
/// </summary>

View File

@ -0,0 +1,81 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.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;
}
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="data">Строка</param>
/// <returns>Объект или null</returns>
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,14 +22,14 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - удачно, false - вставка не удалась</returns>
int Insert(T obj);
int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - удачно, false - вставка не удалась</returns>
bool Insert(T obj, int position);
bool Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
@ -54,4 +54,9 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}

View File

@ -46,22 +46,27 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (_collection.Count + 1 <= _maxCount)
if (Count + 1 <= _maxCount)
{
if (_collection.Contains(obj, comparer))
throw new ObjectExistsException();
_collection.Add(obj);
return _collection.Count - 1;
return Count - 1;
}
throw new CollectionOverflowException(MaxCount);
}
public bool Insert(T obj, int position)
public bool Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (_collection.Count + 1 > MaxCount)
throw new CollectionOverflowException(MaxCount);
if (position < 0 || position >= MaxCount)
throw new PositionOutOfCollectionException(position);
if (_collection.Contains(obj, comparer))
throw new ObjectExistsException();
_collection.Insert(position, obj);
return true;
}
@ -82,4 +87,8 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -1,4 +1,5 @@
using Battleship.Exceptions;
using System;
namespace Battleship.CollectionGenericObjects;
/// <summary>
@ -60,22 +61,27 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
for (int i = 0; i < _collection.Length; i++)
int index = Array.IndexOf(_collection, null);
if (_collection.Contains(obj, comparer))
throw new ObjectExistsException(index);
if (index >= 0)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
_collection[index] = obj;
return index;
}
throw new CollectionOverflowException(_collection.Length);
}
public bool Insert(T obj, int position)
public bool Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (position < 0 || position >= _collection.Length) // проверка позиции
throw new PositionOutOfCollectionException(position);
if (_collection.Contains(obj, comparer))
throw new ObjectExistsException(position);
if (_collection[position] == null) // Попытка вставить на указанную позицию
{
_collection[position] = obj;
@ -118,4 +124,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
if (_collection?.Length > 0)
{
Array.Sort(_collection, comparer);
Array.Reverse(_collection);
}
}
}

View File

@ -1,5 +1,6 @@
using Battleship.Drawnings;
using Battleship.Exceptions;
using Microsoft.AspNetCore.Http;
using System.Text;
namespace Battleship.CollectionGenericObjects;
@ -14,12 +15,12 @@ public class StorageCollection<T>
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
@ -41,7 +42,7 @@ public class StorageCollection<T>
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@ -51,15 +52,16 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name))
CollectionInfo tempInfo = new(name, collectionType, string.Empty);
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(tempInfo))
return;
switch (collectionType)
{
case CollectionType.List:
_storages.Add(name, new ListGenericObjects<T>());
_storages.Add(tempInfo, new ListGenericObjects<T>());
break;
case CollectionType.Massive:
_storages.Add(name, new MassiveGenericObjects<T>());
_storages.Add(tempInfo, new MassiveGenericObjects<T>());
break;
default:
break;
@ -72,8 +74,9 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
if (_storages.ContainsKey(name)) //??? спрросить, зачем проверка
_storages.Remove(name);
CollectionInfo tempInfo = new(name, CollectionType.None, string.Empty);
if (tempInfo.Name != null && _storages.ContainsKey(tempInfo))
_storages.Remove(tempInfo);
}
/// <summary>
@ -85,10 +88,10 @@ public class StorageCollection<T>
{
get
{
if (_storages.TryGetValue(name, out ICollectionGenericObjects<T>? value))
return value;
return null;
}
CollectionInfo tempInfo = new(name, CollectionType.None, string.Empty);
if (tempInfo == null || !_storages.ContainsKey(tempInfo)) { return null; }
return _storages[tempInfo];
}
}
/// <summary>
/// Сохранение информации по кораблям в хранилище в файл
@ -97,31 +100,27 @@ public class StorageCollection<T>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder sb = new();
using (StreamWriter sw = new StreamWriter(filename))
{
sw.WriteLine(_collectionKey.ToString());
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> kvpair in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> kvpair in _storages)
{
// не сохраняем пустые коллекции
if (kvpair.Value.Count == 0)
continue;
sb.Append(kvpair.Key);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in kvpair.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
@ -143,9 +142,7 @@ public class StorageCollection<T>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader sr = new StreamReader(filename))
{
@ -157,20 +154,19 @@ public class StorageCollection<T>
while ((str = sr.ReadLine()) != null)
{
string[] record = str.Split(_separatorForKeyValue);
if (record.Length != 4)
if (record.Length != 3)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции:" + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType);
if (collection == null)
{
throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningShip() is T ship)
@ -188,7 +184,7 @@ public class StorageCollection<T>
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}

View File

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.Drawnings;
public class DrawningCompareByColor : IComparer<DrawningShip?>
{
public int Compare(DrawningShip? x, DrawningShip? y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null || x.EntityShip == null)
{
return -1;
}
if (y == null || y.EntityShip == null)
{
return 1;
}
if (x.EntityShip.BodyColor.Name != y.EntityShip.BodyColor.Name)
{
return x.EntityShip.BodyColor.Name.CompareTo(y.EntityShip.BodyColor.Name);
}
var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight);
}
}

View File

@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.Drawnings;
public class DrawningCompareByType : IComparer<DrawningShip?>
{
public int Compare(DrawningShip? x, DrawningShip? y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null || x.EntityShip == null)
{
return -1;
}
if (y == null || y.EntityShip == null)
{
return 1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight);
}
}

View File

@ -0,0 +1,68 @@
using Battleship.Entities;
using System.Diagnostics.CodeAnalysis;
namespace Battleship.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawningShipEqutables : IEqualityComparer<DrawningShip?>
{
public bool Equals(DrawningShip? x, DrawningShip? y)
{
if (x == null || x.EntityShip == null)
{
return false;
}
if (y == null || y.EntityShip == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityShip.Speed != y.EntityShip.Speed)
{
return false;
}
if (x.EntityShip.Weight != y.EntityShip.Weight)
{
return false;
}
if (x.EntityShip.BodyColor != y.EntityShip.BodyColor)
{
return false;
}
if (x is DrawningBattleship && y is DrawningBattleship)
{
EntityBattleship EntityX = (EntityBattleship)x.EntityShip;
EntityBattleship EntityY = (EntityBattleship)y.EntityShip;
if (EntityX.Rockets != EntityY.Rockets)
{
return false;
}
if (EntityX.Weapon != EntityY.Weapon)
{
return false;
}
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningShip obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
internal class ObjectExistsException : ApplicationException
{
public ObjectExistsException(int count) : base("Вставка существующего объекта") { }
public ObjectExistsException() : base() { }
public ObjectExistsException(string message) : base(message) { }
public ObjectExistsException(string message, Exception exception) : base(message, exception) { }
protected ObjectExistsException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -52,6 +52,8 @@
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonSortByType = new Button();
buttonSortByColor = new Button();
Tools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@ -75,15 +77,17 @@
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddShip);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonGoToTest);
panelCompanyTools.Controls.Add(buttonDelShip);
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(0, 686);
panelCompanyTools.Location = new Point(0, 639);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(488, 569);
panelCompanyTools.Size = new Size(488, 577);
panelCompanyTools.TabIndex = 8;
//
// buttonAddShip
@ -91,7 +95,7 @@
buttonAddShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddShip.Location = new Point(9, 3);
buttonAddShip.Name = "buttonAddShip";
buttonAddShip.Size = new Size(473, 90);
buttonAddShip.Size = new Size(473, 70);
buttonAddShip.TabIndex = 1;
buttonAddShip.Text = "Добавить корабль";
buttonAddShip.UseVisualStyleBackColor = true;
@ -100,9 +104,9 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(16, 432);
buttonRefresh.Location = new Point(12, 294);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(466, 90);
buttonRefresh.Size = new Size(473, 70);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
@ -111,7 +115,7 @@
// maskedTextBox
//
maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBox.Location = new Point(12, 195);
maskedTextBox.Location = new Point(12, 97);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(470, 39);
@ -121,9 +125,9 @@
// buttonGoToTest
//
buttonGoToTest.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToTest.Location = new Point(16, 336);
buttonGoToTest.Location = new Point(12, 218);
buttonGoToTest.Name = "buttonGoToTest";
buttonGoToTest.Size = new Size(466, 90);
buttonGoToTest.Size = new Size(473, 70);
buttonGoToTest.TabIndex = 5;
buttonGoToTest.Text = "Передать на тест";
buttonGoToTest.UseVisualStyleBackColor = true;
@ -132,9 +136,9 @@
// buttonDelShip
//
buttonDelShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonDelShip.Location = new Point(12, 240);
buttonDelShip.Location = new Point(12, 142);
buttonDelShip.Name = "buttonDelShip";
buttonDelShip.Size = new Size(473, 90);
buttonDelShip.Size = new Size(473, 70);
buttonDelShip.TabIndex = 4;
buttonDelShip.Text = "Удалить корабль";
buttonDelShip.UseVisualStyleBackColor = true;
@ -142,9 +146,9 @@
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(9, 612);
buttonCreateCompany.Location = new Point(6, 584);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(473, 68);
buttonCreateCompany.Size = new Size(473, 49);
buttonCreateCompany.TabIndex = 7;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
@ -162,7 +166,7 @@
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 35);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(482, 512);
panelStorage.Size = new Size(482, 497);
panelStorage.TabIndex = 7;
//
// buttonCollectionDel
@ -238,7 +242,7 @@
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Доки" });
comboBoxSelectorCompany.Location = new Point(9, 566);
comboBoxSelectorCompany.Location = new Point(6, 538);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(476, 40);
comboBoxSelectorCompany.TabIndex = 0;
@ -294,6 +298,26 @@
//
openFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByType
//
buttonSortByType.Location = new Point(12, 389);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(473, 70);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(3, 465);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(473, 70);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// FormShipCollection
//
AutoScaleDimensions = new SizeF(13F, 32F);
@ -343,5 +367,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByType;
private Button buttonSortByColor;
}
}

View File

@ -20,11 +20,11 @@ public partial class FormShipCollection : Form
/// Конструктор
/// </summary>
public FormShipCollection(ILogger<FormShipCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
#region Работа с компанией
/// <summary>
/// Выбор компании
@ -56,11 +56,16 @@ public partial class FormShipCollection : Form
_logger.LogInformation("Не удалось добавить корабль {ship} в коллекцию", ship);
}
}
catch(CollectionOverflowException ex)
catch (CollectionOverflowException ex)
{
MessageBox.Show("Ошибка переполнения коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ObjectExistsException ex)
{
MessageBox.Show("Такой объект есть в коллекции");
_logger.LogWarning($"Добавление существующего объекта: {ex.Message}");
}
}
/// <summary>
/// Кнопка удаления корабля
@ -93,7 +98,7 @@ public partial class FormShipCollection : Form
_logger.LogInformation("Не удалось удалить корабль из коллекции по индексу {pos}", pos);
}
}
catch(ObjectNotFoundException ex)
catch (ObjectNotFoundException ex)
{
MessageBox.Show("Ошибка: отсутствует объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
@ -166,7 +171,7 @@ public partial class FormShipCollection : Form
form.AddEvent(SetShip);
form.Show();
}
#endregion
#region Работа с коллекцией
/// <summary>
@ -222,7 +227,7 @@ public partial class FormShipCollection : Form
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);
@ -273,12 +278,13 @@ public partial class FormShipCollection : Form
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try {
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch(Exception ex)
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
@ -308,4 +314,33 @@ public partial class FormShipCollection : Form
}
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareShips(new DrawningCompareByType());
}
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareShips(new DrawningCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareShips(IComparer<DrawningShip?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}