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

This commit is contained in:
selli73 2024-06-12 23:42:03 +04:00
parent 5585f31293
commit 4aee36bc5c
14 changed files with 410 additions and 138 deletions

View File

@ -40,8 +40,6 @@ public abstract class AbstractCompany
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
//private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
//private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary>
@ -66,7 +64,7 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningLocomotive locomotive)
{
return company._collection.Insert(locomotive);
return company._collection.Insert(locomotive, new DrawningLocomotiveEqutables());
}
/// <summary>
@ -111,7 +109,7 @@ public abstract class AbstractCompany
}
return bitmap;
}
/// <summary>
/// Вывод заднего фона
/// </summary>
@ -122,4 +120,10 @@ public abstract class AbstractCompany
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningLocomotive?> comparer) => _collection?.CollectionSort(comparer);
}

View File

@ -6,6 +6,9 @@ using System.Threading.Tasks;
namespace Monorail.CollectionGenericObjects;
/// <summary>
/// Класс, хранящий информацию по коллекции
/// </summary>
public class CollectionInfo : IEquatable<CollectionInfo>
{
/// <summary>

View File

@ -1,4 +1,5 @@
using System;
using Monorail.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -23,16 +24,18 @@ public interface ICollectionGenericObjects <T>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// /// <param name="comparer">Сравнение двух объектов</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>
/// /// <param name="comparer">Сравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position);
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
@ -58,4 +61,10 @@ public interface ICollectionGenericObjects <T>
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer"></param>
void CollectionSort(IComparer<T?> comparer);
}

View File

@ -1,4 +1,5 @@
using Monorail.Exceptions;
using Monorail.Drawnings;
using Monorail.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -64,9 +65,17 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
// TODO выброс ошибки если переполнение
// Проверка, что такой объект уже есть
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectIsEqualException();
}
}
// Проверка, что не превышено максимальное количество элементов
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
@ -75,10 +84,17 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return Count;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
// TODO выброс ошибки если переполнение
// TODO выброс ошибки если за границу
//Проверка, что такой объект уже есть
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectNotFoundException();
}
}
// Проверка, что не превышено максимальное количество элементов
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
@ -111,4 +127,10 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -1,4 +1,5 @@
using Monorail.Exceptions;
using Monorail.Drawnings;
using Monorail.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -44,9 +45,6 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
/// <summary>
/// Конструктор
/// </summary>
@ -55,7 +53,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
_collection = Array.Empty<T?>();
}
public T? Get(int position)
public T Get(int position)
{
// TODO выброс ошибки если выход за границу
// TODO выброс ошибки если объект пустой
@ -70,42 +68,69 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
// Вставка в свободное место набора
return Insert(obj, 0);
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningLocomotive>).Equals(obj as DrawningLocomotive, item as DrawningLocomotive))
throw new ObjectIsEqualException();
}
}
int index = 0;
while (index < _collection.Length)
{
if (_collection[index] == null)
{
_collection[index] = obj;
return index;
}
++index;
}
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
// TODO выбрас ошибки, если есть такой объект в коллекции
// Проверка позиции
if (position < 0 || position >= Count)
if (comparer != null)
{
throw new PositionOutOfCollectionException(position);
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningLocomotive>).Equals(obj as DrawningLocomotive, item as DrawningLocomotive))
throw new ObjectIsEqualException();
}
}
// Проверка, что элемент массива по этой позиции пустой
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
{
_collection[position] = obj;
return position;
}
//Свободное место после этой позиции
for (int i = position + 1; i < Count; i++)
int index = position + 1;
while (index < _collection.Length)
{
if (_collection[i] == null)
if (_collection[index] == null)
{
_collection[i] = obj;
return i;
_collection[index] = obj;
return index;
}
++index;
}
//Свободное место до этой позиции
for (int i = position - 1; i >= 0; i--)
index = position - 1;
while (index >= 0)
{
if (_collection[i] == null)
if (_collection[index] == null)
{
_collection[i] = obj;
return i;
_collection[index] = obj;
return index;
}
--index;
}
throw new CollectionOverflowException(Count);
}
@ -137,5 +162,15 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
//public void CollectionSort(IComparer<T?> comparer)
//{
// Array.Sort(_collection, comparer);
//}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -18,19 +18,19 @@ 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>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@ -42,18 +42,13 @@ public class StorageCollection<T>
{
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name) || collectionType == CollectionType.None)
{
return;
}
if (collectionType == CollectionType.Massive)
{
_storages[name] = new MassiveGenericObjects<T>();
}
if (collectionType == CollectionType.List)
{
_storages[name] = new ListGenericObjects<T>();
}
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (_storages.ContainsKey(collectionInfo)) return;
if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive)
_storages[collectionInfo] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List)
_storages[collectionInfo] = new ListGenericObjects<T>();
}
/// <summary>
@ -63,10 +58,9 @@ 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>
@ -78,14 +72,10 @@ public class StorageCollection<T>
{
get
{
if (_storages.ContainsKey(name))
{
return _storages[name];
}
else
{
return null;
}
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
return _storages[collectionInfo];
return null;
}
}
@ -112,7 +102,7 @@ public class StorageCollection<T>
{
if (_storages.Count == 0)
{
throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения");
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
@ -123,7 +113,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)
{
writer.Write(Environment.NewLine);
// не сохраняем пустые коллекции
@ -133,8 +123,6 @@ public class StorageCollection<T>
}
writer.Write(value.Key);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.GetCollectionType);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.MaxCount);
writer.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
@ -158,36 +146,40 @@ public class StorageCollection<T>
{
if (!File.Exists(filename))
{
throw new Exception("Файл не существует");
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader fs = File.OpenText(filename))
using (StreamReader read = File.OpenText(filename))
{
string str = fs.ReadLine();
string str = read.ReadLine();
if (str == null || str.Length == 0)
{
throw new Exception("В файле нет данных");
}
if (!str.StartsWith(_collectionKey))
{
throw new Exception("В файле неверные данные");
}
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
while ((strs = read.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
if (record.Length != 3)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
throw new Exception("Не удалось определить тип коллекции:" + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new InvalidOperationException("Не удалось создать коллекцию");
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningLocomotive() is T locomotive)
@ -195,7 +187,9 @@ public class StorageCollection<T>
try
{
if (collection.Insert(locomotive) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
@ -203,7 +197,7 @@ public class StorageCollection<T>
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,74 @@
using Monorail.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monorail.Drawnings;
public class DrawningLocomotiveEqutables : IEqualityComparer<DrawningLocomotive?>
{
public bool Equals(DrawningLocomotive? x, DrawningLocomotive? y)
{
if (x == null || x.EntityLocomotive == null)
{
return false;
}
if (y == null || y.EntityLocomotive == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityLocomotive.Speed != y.EntityLocomotive.Speed)
{
return false;
}
if (x.EntityLocomotive.Weight != y.EntityLocomotive.Weight)
{
return false;
}
if (x.EntityLocomotive.BodyColor != y.EntityLocomotive.BodyColor)
{
return false;
}
if (x is DrawningMonorail && y is DrawningMonorail)
{
// TODO доделать логику сравнения дополнительных параметров
EntityMonorail EntityX = (EntityMonorail)x.EntityLocomotive;
EntityMonorail EntityY = (EntityMonorail)y.EntityLocomotive;
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
{
return false;
}
if (EntityX.MagneticRail != EntityY.MagneticRail)
{
return false;
}
if (EntityX.SecondCabin != EntityY.SecondCabin)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningLocomotive obj)
{
return obj.GetHashCode();
}
}

View File

@ -8,7 +8,7 @@ using System.Threading.Tasks;
namespace Monorail.Drawnings;
/// <summary>
/// Расширение для класса EntityCar
/// Расширение для класса EntityLocomotive
/// </summary>
public static class ExtentionDrawningLocomotive
{

View File

@ -1,17 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Monorail.Exceptions;
[Serializable]
internal class AlreadyInCollectionException : ApplicationException
{
public AlreadyInCollectionException() : base("Такой объект уже есть в коллекции") { }
public AlreadyInCollectionException(string message) : base(message) { }
public AlreadyInCollectionException(string message, Exception exception) : base(message, exception) { }
protected AlreadyInCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Monorail.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
internal class ObjectIsEqualException : ApplicationException
{
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();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonSortByType = new Button();
buttonSortByColor = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@ -68,13 +70,15 @@
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(752, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(187, 548);
groupBoxTools.Size = new Size(187, 600);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonAddLocomotive);
panelCompanyTools.Controls.Add(buttonRemoveLocomotiv);
@ -82,15 +86,15 @@
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 292);
panelCompanyTools.Location = new Point(3, 298);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(181, 253);
panelCompanyTools.Size = new Size(181, 299);
panelCompanyTools.TabIndex = 9;
//
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(13, 176);
buttonGoToCheck.Location = new Point(13, 131);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(156, 39);
buttonGoToCheck.TabIndex = 5;
@ -112,7 +116,7 @@
// buttonRemoveLocomotiv
//
buttonRemoveLocomotiv.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveLocomotiv.Location = new Point(13, 131);
buttonRemoveLocomotiv.Location = new Point(13, 86);
buttonRemoveLocomotiv.Name = "buttonRemoveLocomotiv";
buttonRemoveLocomotiv.Size = new Size(156, 39);
buttonRemoveLocomotiv.TabIndex = 4;
@ -122,7 +126,7 @@
//
// maskedTextBox
//
maskedTextBox.Location = new Point(13, 102);
maskedTextBox.Location = new Point(13, 57);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(156, 23);
@ -132,7 +136,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(13, 221);
buttonRefresh.Location = new Point(13, 176);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(156, 39);
buttonRefresh.TabIndex = 6;
@ -249,7 +253,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(752, 548);
pictureBox.Size = new Size(752, 600);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -293,11 +297,31 @@
//
openFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByType
//
buttonSortByType.Location = new Point(13, 221);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(156, 32);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(13, 259);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(156, 31);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// FormLocomotiveCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(939, 572);
ClientSize = new Size(939, 624);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@ -342,5 +366,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -29,7 +29,7 @@ public partial class FormLocomotiveCollection : Form
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
@ -37,7 +37,7 @@ public partial class FormLocomotiveCollection : Form
/// <summary>
/// Конструктор
/// </summary>z
public FormLocomotiveCollection(ILogger <FormLocomotiveCollection> logger)
public FormLocomotiveCollection(ILogger<FormLocomotiveCollection> logger)
{
InitializeComponent();
_storageCollection = new();
@ -92,6 +92,11 @@ public partial class FormLocomotiveCollection : Form
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ObjectIsEqualException ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
@ -136,17 +141,7 @@ public partial class FormLocomotiveCollection : Form
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
/*
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
*/
}
@ -215,28 +210,22 @@ public partial class FormLocomotiveCollection : Form
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены");
return;
}
try
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
collectionType = CollectionType.Massive;
}
catch (Exception ex)
else if (radioButtonList.Checked)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
_logger.LogInformation("Добавлена коллекция типа " + collectionType + " с названием "
+ textBoxCollectionName.Text);
}
/// <summary>
///
@ -279,7 +268,7 @@ public partial class FormLocomotiveCollection : 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);
@ -334,12 +323,12 @@ public partial class FormLocomotiveCollection : Form
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch(Exception ex)
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
@ -366,4 +355,39 @@ public partial class FormLocomotiveCollection : Form
}
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareLocomotive(new DrawningLocomotiveCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareLocomotive(new DrawningLocomotiveCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareLocomotive(IComparer<DrawningLocomotive?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}