ISEbd-11_Sharonov_I.A.Lab08_Simple #8

Closed
357Sharonov wants to merge 2 commits from Lab08 into Lab07
13 changed files with 395 additions and 87 deletions

View File

@ -10,32 +10,26 @@ public abstract class AbstractCompany
/// Размер места (ширина)
/// </summary>
protected readonly int _placeSizeWidth = 180;
/// <summary>
/// Размер места (высота)
/// </summary>
protected readonly int _placeSizeHeight = 100;
/// <summary>
/// Ширина окна
/// </summary>
protected readonly int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
protected readonly int _pictureHeight;
/// <summary>
/// Коллекция cамолетов
/// </summary>
protected ICollectionGenericObjects<DrawingBasicSeaplane>? _collection = null;
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => (_pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight))-15;
/// <summary>
/// Конструктор
/// </summary>
@ -49,7 +43,6 @@ public abstract class AbstractCompany
_collection = collection;
_collection.MaxCount = GetMaxCount;
}
/// <summary>
/// Перегрузка оператора сложения для класса
/// </summary>
@ -58,9 +51,8 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawingBasicSeaplane seaplane)
{
return company._collection.Insert(seaplane);
return company._collection.Insert(seaplane, new DrawingSeaplaneEqutables());
}
/// <summary>
/// Перегрузка оператора удаления для класса
/// </summary>
@ -71,7 +63,6 @@ public abstract class AbstractCompany
{
return company._collection?.Remove(position);
}
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>
@ -81,7 +72,6 @@ public abstract class AbstractCompany
Random rnd = new();
return _collection?.Get(rnd.Next(GetMaxCount));
}
/// <summary>
/// Вывод всей коллекции
/// </summary>
@ -105,15 +95,18 @@ public abstract class AbstractCompany
return bitmap;
}
/// <summary>
/// Вывод заднего фона
/// </summary>
/// <param name="g"></param>
protected abstract void DrawBackgound(Graphics g);
/// <summary>
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawingBasicSeaplane?> comparer) => _collection?.CollectionSort(comparer);
}

View File

@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSeaplane.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

@ -11,34 +11,29 @@ public interface ICollectionGenericObjects<T>
/// Количество объектов в коллекции
/// </summary>
int Count { get; }
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
int Insert(T obj, IEqualityComparer<T?>? compaper = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position);
int Insert(T obj, int position, IEqualityComparer<T?>? compaper = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
T Remove(int position);
/// <summary>
/// Получение объекта по позиции
/// </summary>
@ -54,4 +49,9 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <returns></returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}

View File

@ -31,7 +31,6 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
/// </summary>
@ -45,19 +44,33 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? compaper = null)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO вставка в конец набора
if (compaper != null)
{
if (_collection.Contains(obj, compaper))
{
throw new ObjectIsEqualException();
}
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? compaper = null)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO проверка позиции
// TODO вставка по позиции
if (compaper != null)
{
if (_collection.Contains(obj, compaper))
{
throw new ObjectIsEqualException();
}
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
@ -72,7 +85,6 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
_collection.RemoveAt(position);
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; i++)
@ -80,4 +92,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 ProjectSeaplane.Drawnings;
using ProjectSeaplane.Exceptions;
namespace ProjectSeaplane.CollectionGenericObjects;
@ -38,7 +39,6 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
@ -56,9 +56,17 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? compaper = null)
{
// TODO вставка в свободное место набора
if (compaper != null)
{
foreach (T? item in _collection)
{
if ((compaper as IEqualityComparer<DrawingBasicSeaplane>).Equals(obj as DrawingBasicSeaplane, item as DrawingBasicSeaplane))
throw new ObjectIsEqualException();
}
}
int index = 0;
while (index < _collection.Length)
{
@ -73,25 +81,31 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? compaper = null)
{
// TODO проверка позиции
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до
// TODO вставка
if (compaper != null)
{
foreach (T? item in _collection)
{
if ((compaper as IEqualityComparer<DrawingBasicSeaplane>).Equals(obj as DrawingBasicSeaplane, item as DrawingBasicSeaplane))
throw new ObjectIsEqualException();
}
}
if (position >= _collection.Length || position < 0)
{
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)
@ -100,7 +114,6 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return position;
}
}
for (index = position - 1; index >= 0; --index)
{
if (_collection[index] == null)
@ -111,7 +124,6 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
throw new CollectionOverflowException(Count);
}
public T Remove(int position)
{
// TODO проверка позиции
@ -122,7 +134,6 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
_collection[position] = null;
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; i++)
@ -130,4 +141,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -13,34 +13,29 @@ 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>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
@ -52,12 +47,13 @@ public class StorageCollection<T>
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления
if (_storages.ContainsKey(name)) 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[name] = new MassiveGenericObjects<T>();
_storages[collectionInfo] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List)
_storages[name] = new ListGenericObjects<T>();
_storages[collectionInfo] = new ListGenericObjects<T>();
}
/// <summary>
/// Удаление коллекции
@ -66,10 +62,10 @@ public class StorageCollection<T>
public void DelCollection(string name)
{
// TODO Прописать логику для удаления коллекции
if (_storages.ContainsKey(name))
_storages.Remove(name);
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
_storages.Remove(collectionInfo);
}
/// <summary>
/// Доступ к коллекции
/// </summary>
@ -80,13 +76,14 @@ public class StorageCollection<T>
get
{
// TODO Продумать логику получения объекта
if (_storages.ContainsKey(name))
return _storages[name];
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
return _storages[collectionInfo];
return null;
}
}
}
/// <summary>
/// Сохранение информации по самолетам в хранилище в файл
/// </summary>
@ -106,7 +103,7 @@ public class StorageCollection<T>
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
@ -117,8 +114,6 @@ public class StorageCollection<T>
}
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())
@ -165,18 +160,18 @@ public class StorageCollection<T>
{
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<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 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?.CreateDrawningBasicSeaplane() is T seaplane)
@ -193,7 +188,7 @@ public class StorageCollection<T>
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}

View File

@ -0,0 +1,65 @@
using ProjectSeaplane.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSeaplane.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawingSeaplaneEqutables : IEqualityComparer<DrawingBasicSeaplane?>
{
public bool Equals(DrawingBasicSeaplane? x, DrawingBasicSeaplane? y)
{
if (x == null || x.EntityBasicSeaplane == null)
{
return false;
}
if (y == null || y.EntityBasicSeaplane == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityBasicSeaplane.Speed != y.EntityBasicSeaplane.Speed)
{
return false;
}
if (x.EntityBasicSeaplane.Weight != y.EntityBasicSeaplane.Weight)
{
return false;
}
if (x.EntityBasicSeaplane.BodyColor != y.EntityBasicSeaplane.BodyColor)
{
return false;
}
if (x is EntitySeaplane && y is EntitySeaplane)
{
// TODO доделать логику сравнения дополнительных параметров
EntitySeaplane _x = (EntitySeaplane)x.EntityBasicSeaplane;
EntitySeaplane _y = (EntitySeaplane)x.EntityBasicSeaplane;
if (_x.AdditionalColor != _y.AdditionalColor)
{
return false;
}
if (_x.Radar != _y.Radar)
{
return false;
}
if (_x.LandingGear != _y.LandingGear)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawingBasicSeaplane? obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSeaplane.Drawnings;
/// <summary>
/// сравнение по цвету, скорости и весу
/// </summary>
public class SeaplaneCompareByColor : IComparer<DrawingBasicSeaplane?>
{
public int Compare(DrawingBasicSeaplane? x, DrawingBasicSeaplane? y)
{
if (x == null || x.EntityBasicSeaplane == null)
{
return 1;
}
if (y == null || y.EntityBasicSeaplane == null)
{
return -1;
}
var bodycolorCompare = x.EntityBasicSeaplane.BodyColor.Name.CompareTo(y.EntityBasicSeaplane.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityBasicSeaplane.Speed.CompareTo(y.EntityBasicSeaplane.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBasicSeaplane.Weight.CompareTo(y.EntityBasicSeaplane.Weight);
}
}

View File

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

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSeaplane.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();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@ -75,15 +77,17 @@
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddBasicSeaplane);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonDelSeaplane);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Location = new Point(3, 361);
panelCompanyTools.Location = new Point(3, 301);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(174, 226);
panelCompanyTools.Size = new Size(174, 286);
panelCompanyTools.TabIndex = 9;
//
// buttonAddBasicSeaplane
@ -102,7 +106,7 @@
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.FlatStyle = FlatStyle.Flat;
buttonRefresh.Location = new Point(0, 183);
buttonRefresh.Location = new Point(0, 148);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(174, 31);
buttonRefresh.TabIndex = 6;
@ -112,7 +116,7 @@
//
// maskedTextBox
//
maskedTextBox.Location = new Point(0, 83);
maskedTextBox.Location = new Point(0, 48);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(174, 23);
@ -123,7 +127,7 @@
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.FlatStyle = FlatStyle.Flat;
buttonGoToCheck.Location = new Point(0, 148);
buttonGoToCheck.Location = new Point(0, 113);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(174, 29);
buttonGoToCheck.TabIndex = 5;
@ -135,7 +139,7 @@
//
buttonDelSeaplane.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonDelSeaplane.FlatStyle = FlatStyle.Flat;
buttonDelSeaplane.Location = new Point(0, 112);
buttonDelSeaplane.Location = new Point(0, 77);
buttonDelSeaplane.Name = "buttonDelSeaplane";
buttonDelSeaplane.Size = new Size(174, 30);
buttonDelSeaplane.TabIndex = 4;
@ -145,9 +149,9 @@
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(3, 334);
buttonCreateCompany.Location = new Point(3, 269);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(171, 26);
buttonCreateCompany.Size = new Size(174, 26);
buttonCreateCompany.TabIndex = 8;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
@ -165,12 +169,12 @@
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 19);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(174, 280);
panelStorage.Size = new Size(174, 219);
panelStorage.TabIndex = 7;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(0, 234);
buttonCollectionDel.Location = new Point(0, 189);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(171, 26);
buttonCollectionDel.TabIndex = 6;
@ -184,7 +188,7 @@
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(3, 104);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(168, 124);
listBoxCollection.Size = new Size(168, 79);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
@ -240,9 +244,9 @@
СomboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
СomboBoxSelectorCompany.FormattingEnabled = true;
СomboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
СomboBoxSelectorCompany.Location = new Point(3, 305);
СomboBoxSelectorCompany.Location = new Point(3, 240);
СomboBoxSelectorCompany.Name = "СomboBoxSelectorCompany";
СomboBoxSelectorCompany.Size = new Size(171, 23);
СomboBoxSelectorCompany.Size = new Size(174, 23);
СomboBoxSelectorCompany.TabIndex = 0;
СomboBoxSelectorCompany.SelectedIndexChanged += СomboBoxSelectorCompany_SelectedIndexChanged;
//
@ -295,6 +299,30 @@
//
saveFileDialog.Filter = "txt file |*.txt";
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.FlatStyle = FlatStyle.Flat;
buttonSortByColor.Location = new Point(0, 230);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(171, 37);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.FlatStyle = FlatStyle.Flat;
buttonSortByType.Location = new Point(0, 185);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(171, 39);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// FormPlaneCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
@ -344,5 +372,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -87,9 +87,12 @@ public partial class FormPlaneCollection : Form
MessageBox.Show("Выход за границы коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ObjectIsEqualException ex)
{
MessageBox.Show("Не удалось добавить объект, такой объект уже является частью коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
/// Удаление объекта
/// </summary>
@ -101,12 +104,10 @@ public partial class FormPlaneCollection : Form
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
try
{
@ -123,7 +124,6 @@ public partial class FormPlaneCollection : Form
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
/// Передача объекта в другую форму
/// </summary>
@ -167,7 +167,6 @@ public partial class FormPlaneCollection : Form
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Перерисовка коллекции
/// </summary>
@ -182,9 +181,6 @@ public partial class FormPlaneCollection : Form
pictureBox.Image = _company.Show();
}
/// <summary>
/// добавление коллекции
/// </summary>
@ -228,14 +224,13 @@ public partial class FormPlaneCollection : 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);
}
}
}
/// <summary>
/// удаление коллекции
/// </summary>
@ -292,7 +287,6 @@ public partial class FormPlaneCollection : Form
RerfreshListBoxItems();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
@ -317,7 +311,6 @@ public partial class FormPlaneCollection : Form
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
@ -342,5 +335,36 @@ public partial class FormPlaneCollection : Form
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareSeaplane(new SeaplaneCompareByType());
}
/// <summary>
/// Cортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareSeaplane(new SeaplaneCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareSeaplane(IComparer<DrawingBasicSeaplane?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}

View File

@ -126,4 +126,7 @@
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>271, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>50</value>
</metadata>
</root>