LabWork08

This commit is contained in:
Сафия Мухамадиева 2024-06-02 15:22:39 +03:00
parent ead2dcee19
commit b6d4f83ae7
16 changed files with 298 additions and 160 deletions

View File

@ -55,7 +55,8 @@ public abstract class AbstractCompany
public static int operator +(AbstractCompany company,
DrawingWarship warship)
{
return company._collection?.Insert(warship, new DrawiningWarshipEqutables()) ?? 0;
return company._collection?.Insert(warship, new DrawingWarshipEqutables()) ??
throw new DrawningEquitablesException();
}
/// <summary>
/// Перегрузка оператора удаления для класса
@ -81,7 +82,7 @@ public abstract class AbstractCompany
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningAircraft?> comparer) => _collection?.CollectionSort(comparer);
public void Sort(IComparer<DrawingWarship?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Вывод всей коллекции
/// </summary>

View File

@ -0,0 +1,82 @@
namespace ProjectBattleship.CollectionGenericObjects;
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 bool IsEmpty()
{
if (string.IsNullOrEmpty(Name) && CollectionType != CollectionType.None) return true;
return false;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}

View File

@ -22,25 +22,23 @@ where T : class
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="comparer">Сравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, IEqualityComparer<DrawingWarship?>? comparer = null);
int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <param name="comparer">Сравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position, IEqualityComparer<DrawingWarship?>? comparer = null);
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
T? Remove(int position);
T Remove(int position);
/// <summary>
/// Получение объекта по позиции

View File

@ -3,7 +3,7 @@ using ProjectBattleship.DrawingObject;
using ProjectBattleship.Exceptions;
namespace Battleship.CollectionGenericObjects;
namespace ProjectBattleship.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
@ -53,10 +53,9 @@ where T : class
return _collection[position];
}
public int Insert(T obj, IEqualityComparer<DrawingWarship?>? comparer = null)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (comparer != null)
{
for (int i = 0; i < Count; i++)
@ -71,8 +70,7 @@ where T : class
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position, IEqualityComparer<DrawingWarship?>? comparer = null)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
@ -88,7 +86,6 @@ where T : class
}
}
_collection.Insert(position, obj);
return position;
}
@ -108,7 +105,6 @@ where T : class
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);

View File

@ -2,7 +2,7 @@
using ProjectBattleship.CollectionGenericObjects;
using ProjectBattleship.DrawingObject;
namespace Battleship.CollectionGenericObjects;
namespace ProjectBattleship.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
/// </summary>
@ -61,7 +61,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj, IEqualityComparer<DrawingWarship?>? comparer = null)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
@ -74,6 +74,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
// вставка в свободное место набора
for (int i = 0; i < Count; i++)
{
@ -87,7 +88,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position, IEqualityComparer<DrawingWarship?>? comparer = null)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
// проверка позиции
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
@ -135,14 +136,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
// вставка
_collection[position] = obj;
return position;
}
public T? Remove(int position)
{
// проверка позиции
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
@ -151,6 +151,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
_collection[position] = null;
return temp;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
@ -158,7 +159,6 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
List<T?> value = new List<T?>(_collection);

View File

@ -1,23 +1,20 @@
using ProjectBattleship.CollectionGenericObjects;
using ProjectBattleship.Exceptions;
using ProjectBattleship.DrawingObject;
using ProjectBattleship.Exceptions;
using System.Text;
namespace Battleship.CollectionGenericObjects;
namespace ProjectBattleship.CollectionGenericObjects;
/// <summary>
/// Класс-хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T> where T : DrawingWarship
public class StorageCollection<T>
where T : DrawingWarship
{
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
private Dictionary<string, ICollectionGenericObjects<T>> _storages;
private Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
@ -39,91 +36,82 @@ public class StorageCollection<T> where T : DrawingWarship
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
/// </summary>
/// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
/// <param name="collectionInfo">тип коллекции</param>
public void AddCollection(CollectionInfo collectionInfo)
{
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name))
return;
switch (collectionType)
{
case CollectionType.List:
_storages.Add(name, new ListGenericObjects<T>());
break;
case CollectionType.Massive:
_storages.Add(name, new MassiveGenericObjects<T>());
break;
default:
break;
}
if (_storages.ContainsKey(collectionInfo)) throw new CollectionAlreadyExistsException(collectionInfo);
if (collectionInfo.CollectionType == CollectionType.None)
throw new CollectionTypeException("Пустой тип коллекции");
if (collectionInfo.CollectionType == CollectionType.Massive)
_storages[collectionInfo] = new MassiveGenericObjects<T>();
else if (collectionInfo.CollectionType == CollectionType.List)
_storages[collectionInfo] = new ListGenericObjects<T>();
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
/// <param name="collectionInfo">тип коллекции</param>
public void DelCollection(CollectionInfo collectionInfo)
{
if (_storages.ContainsKey(name)) { _storages.Remove(name); }
if (_storages.ContainsKey(collectionInfo))
_storages.Remove(collectionInfo);
}
/// <summary>
/// Доступ к коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
/// <param name="collectionInfo"></param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[string name]
public ICollectionGenericObjects<T>? this[CollectionInfo collectionInfo]
{
get
{
if (_storages.TryGetValue(name, out ICollectionGenericObjects<T>? value))
return value;
if (_storages.ContainsKey(collectionInfo))
return _storages[collectionInfo];
return null;
}
}
/// <summary>
/// Сохранение информации по самолетам в хранилище в файл
/// Сохранение информации по самолетам в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
/// <param name="filename"></param>
/// <exception cref="EmptyFileExeption"></exception>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
throw new EmptyFileException();
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using FileStream fs = new(filename, FileMode.Create);
using StreamWriter streamWriter = new StreamWriter(fs);
streamWriter.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
using (StreamWriter writer = new StreamWriter(filename))
{
streamWriter.Write(Environment.NewLine);
writer.Write(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
if (value.Value.Count == 0)
{
continue;
}
streamWriter.Write(value.Key);
streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.GetCollectionType);
streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.MaxCount);
streamWriter.Write(_separatorForKeyValue);
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
@ -132,73 +120,86 @@ public class StorageCollection<T> where T : DrawingWarship
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
}
streamWriter.Write(data);
streamWriter.Write(_separatorItems);
writer.Write(sb);
}
}
}
/// <summary>
/// Загрузка информации по кораблям в хранилище из файла
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename"></param>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new System.IO.FileNotFoundException("Файл не существует");
throw new Exceptions.FileNotFoundException(filename);
}
using (StreamReader sr = new StreamReader(filename))
using (StreamReader fs = File.OpenText(filename))
{
string? str;
str = sr.ReadLine();
if (str != _collectionKey.ToString())
throw new FormatException("В файле неверные данные");
string str = fs.ReadLine();
if (string.IsNullOrEmpty(str))
{
throw new EmptyFileException(filename);
}
if (!str.StartsWith(_collectionKey))
{
throw new Exceptions.FileFormatException(filename);
}
_storages.Clear();
while ((str = sr.ReadLine()) != null)
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
string[] record = str.Split(_separatorForKeyValue);
if (record.Length != 4)
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 3)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
CollectionInfo? collectionInfo =
CollectionInfo.GetCollectionInfo(record[0]) ??
throw new CollectionInfoException("Не удалось определить информацию коллекции:" + record[0]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
ICollectionGenericObjects<T>? collection =
StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new CollectionTypeException("Не удалось определить тип коллекции:" + record[1]);
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawingWarship() is T Warship)
if (elem?.CreateDrawingWarship() is T ship)
{
try
{
if (collection.Insert(Warship) == -1)
collection.Insert(ship);
}
catch (Exception ex)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
throw new Exceptions.FileFormatException(filename, ex);
}
}
catch (CollectionOverflowException ex)
}
_storages.Add(collectionInfo, collection);
}
}
}
private static ICollectionGenericObjects<T>?
CreateCollection(CollectionType collectionType)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
}
}
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType) => collectionType switch
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

@ -1,5 +1,5 @@
using ProjectBattleship.DrawingObject;
namespace Battleship;
namespace ProjectBattleship;
public class DrawingWarshipCompareByColor : IComparer<DrawingWarship?>
{

View File

@ -1,5 +1,5 @@
using ProjectBattleship.DrawingObject;
namespace Battleship;
namespace ProjectBattleship;
public class DrawingWarshipCompareByType : IComparer<DrawingWarship?>
{

View File

@ -4,7 +4,7 @@ namespace ProjectBattleship.DrawingObject;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawiningWarshipEqutables : IEqualityComparer<DrawingWarship?>
public class DrawingWarshipEqutables : IEqualityComparer<DrawingWarship?>
{
public bool Equals(DrawingWarship? x, DrawingWarship? y)
{

View File

@ -1,9 +1,10 @@
using System.Runtime.Serialization;
using ProjectBattleship.CollectionGenericObjects;
namespace ProjectBattleship.Exceptions;
public class CollectionAlreadyExistsException : Exception
{
public CollectionAlreadyExistsException() : base() { }
public CollectionAlreadyExistsException(CollectionInfo collectionInfo) : base($"Коллекция {collectionInfo} уже существует!") { }
public CollectionAlreadyExistsException(CollectionInfo collectioninfo) : base($"Коллекция {collectioninfo} уже существует!") { }
public CollectionAlreadyExistsException(string name, Exception exception) :
base($"Коллекция {name} уже существует!", exception)
{ }

View File

@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace ProjectBattleship.Exceptions;
public class EmptyFileException : Exception
{
public EmptyFileException(string name) : base($"Файл {name} пустой ") { }
public EmptyFileException() : base("В хранилище отсутствуют коллекции для сохранения") { }
public EmptyFileException(string name, string message) : base(message) { }
public EmptyFileException(string name, string message, Exception exception) :
base(message, exception)
{ }
protected EmptyFileException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -1,14 +0,0 @@
using System.Runtime.Serialization;
namespace ProjectBattleship.Exceptions;
public class EmptyFileExeption : Exception
{
public EmptyFileExeption(string name) : base($"Файл {name} пустой ") { }
public EmptyFileExeption() : base("В хранилище отсутствуют коллекции для сохранения") { }
public EmptyFileExeption(string name, string message) : base(message) { }
public EmptyFileExeption(string name, string message, Exception exception) :
base(message, exception)
{ }
protected EmptyFileExeption(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -32,6 +32,8 @@ namespace ProjectBattleship
{
groupBoxCollectionTools = new GroupBox();
panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonSortByType = new Button();
buttonRefresh = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonAddWarship = new Button();
@ -70,13 +72,15 @@ namespace ProjectBattleship
groupBoxCollectionTools.Controls.Add(panelCollection);
groupBoxCollectionTools.Location = new Point(699, 27);
groupBoxCollectionTools.Name = "groupBoxCollectionTools";
groupBoxCollectionTools.Size = new Size(279, 653);
groupBoxCollectionTools.Size = new Size(279, 639);
groupBoxCollectionTools.TabIndex = 1;
groupBoxCollectionTools.TabStop = false;
groupBoxCollectionTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonAddWarship);
@ -85,9 +89,29 @@ namespace ProjectBattleship
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(6, 354);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(267, 208);
panelCompanyTools.Size = new Size(267, 279);
panelCompanyTools.TabIndex = 11;
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(8, 243);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(251, 34);
buttonSortByColor.TabIndex = 13;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Location = new Point(8, 203);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(251, 34);
buttonSortByType.TabIndex = 12;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// buttonRefresh
//
buttonRefresh.Location = new Point(8, 163);
@ -244,7 +268,7 @@ namespace ProjectBattleship
pictureBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left;
pictureBox.Location = new Point(0, 51);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(688, 602);
pictureBox.Size = new Size(688, 615);
pictureBox.TabIndex = 2;
pictureBox.TabStop = false;
//
@ -293,7 +317,7 @@ namespace ProjectBattleship
//
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(978, 653);
ClientSize = new Size(978, 666);
Controls.Add(groupBoxCollectionTools);
Controls.Add(pictureBox);
Controls.Add(menuStrip);
@ -337,5 +361,7 @@ namespace ProjectBattleship
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByType;
private Button buttonSortByColor;
}
}

View File

@ -1,6 +1,5 @@
using Battleship.CollectionGenericObjects;
using ProjectBattleship.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using ProjectBattleship.CollectionGenericObjects;
using ProjectBattleship.DrawingObject;
using System.Windows.Forms;
@ -39,7 +38,13 @@ public partial class FormWarshipCollection : Form
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender,
EventArgs e)
{
panelCompanyTools.Enabled = false;
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new Docks(pictureBox.Width, pictureBox.Height,
new MassiveGenericObjects<DrawingWarship>());
break;
}
}
/// <summary>
/// Добавление военного корабля
@ -240,7 +245,7 @@ public partial class FormWarshipCollection : Form
try
{
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_storageCollection.AddCollection(new CollectionInfo(textBoxCollectionName.Text, collectionType, "2"));
_logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems();
}
@ -270,7 +275,8 @@ public partial class FormWarshipCollection : Form
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!);
_storageCollection.DelCollection(collectionInfo!);
_logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems();
}
@ -283,10 +289,10 @@ public partial class FormWarshipCollection : Form
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
CollectionInfo? col = _storageCollection.Keys?[i];
if (!col!.IsEmpty())
{
listBoxCollection.Items.Add(colName);
listBoxCollection.Items.Add(col);
}
}
}
@ -303,9 +309,9 @@ public partial class FormWarshipCollection : Form
MessageBox.Show("Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawingWarship>? collection =
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
ICollectionGenericObjects<DrawingWarship>? collection = _storageCollection[
CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!) ??
new CollectionInfo("", CollectionType.None, "")]; if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
@ -366,4 +372,38 @@ public partial class FormWarshipCollection : Form
}
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareWarships(new DrawingWarshipCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareWarships(new DrawingWarshipCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareWarships(IComparer<DrawingWarship?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}

View File

@ -37,16 +37,9 @@ namespace ProjectBattleship
/// </summary>
/// <param name="WarshipDelegate"></param>
public void AddEvent(Action<DrawingWarship> warshipDelegate)
{
if (WarshipDelegate != null)
{
WarshipDelegate = warshipDelegate;
}
else
{
WarshipDelegate += warshipDelegate;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>