PIbd-12_Bugrov_D.A._Simple LabWork08 #8

Closed
BoiledMilk wants to merge 2 commits from LabWork08 into LabWork07
12 changed files with 350 additions and 52 deletions

View File

@ -59,9 +59,9 @@ public abstract class AbstractCompany
/// <param name="company">Компания</param>
/// <param name="car">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningLocomotive truck)
public static int operator +(AbstractCompany company, DrawningLocomotive locomotive)
{
return company._collection.Insert(truck);
return company._collection.Insert(locomotive, new DrawningLocomotiveEqutables());
}
// <summary>
@ -109,7 +109,10 @@ public abstract class AbstractCompany
}
return bitmap;
}
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningLocomotive?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Вывод заднего фона
/// </summary>

View File

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

@ -1,4 +1,5 @@
using System;
using ProjectElectricLocomotive.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -11,7 +12,7 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects;
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public interface ICollectionGenericObjects<T>
where T : class
where T : DrawningLocomotive
{
/// <summary>
/// Количество объектов в коллекции
@ -28,13 +29,13 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
int Insert(T obj, IEqualityComparer<DrawningLocomotive?>? comparer = null);
/// <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<DrawningLocomotive?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
@ -58,5 +59,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 ProjectElectricLocomotive.Exceptions;
using ProjectElectricLocomotive.Drawnings;
using ProjectElectricLocomotive.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -8,7 +9,7 @@ using System.Threading.Tasks;
namespace ProjectElectricLocomotive.CollectionGenericObjects;
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
where T : DrawningLocomotive
{
/// <summary>
/// Список объектов, которые храним
@ -60,20 +61,22 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
}
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<DrawningLocomotive?>? comparer = null)
{
if (_collection.Contains(obj, comparer)) throw new AlreadyExistingObject(obj.GetDataForSave());
if (Count == _maxCount) throw new CollectionOwerflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<DrawningLocomotive?>? comparer = null)
{
// проверка, что не превышено максимальное количество элементов
// проверка позиции
// вставка по позиции
if (_collection.Contains(obj, comparer)) throw new AlreadyExistingObject(obj.GetDataForSave());
if (position > MaxCount) throw new CollectionOwerflowException(position);
if (obj == null) throw new ArgumentNullException(nameof(obj));
@ -107,4 +110,10 @@ 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 ProjectElectricLocomotive.Exceptions;
using ProjectElectricLocomotive.Drawnings;
using ProjectElectricLocomotive.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -12,7 +13,7 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects;
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
where T : DrawningLocomotive
{
/// <summary>
/// Массив объектов, которые храним
@ -66,9 +67,10 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
throw new PositionOutOfCollectionException(position);
}
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<DrawningLocomotive?>? comparer = null)
{
// вставка в свободное место набора
if (_collection.Contains(obj, comparer)) throw new AlreadyExistingObject(obj.GetDataForSave());
for (int i = 0; i < Count; ++i)
{
if (_collection[i] == null)
@ -81,17 +83,14 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<DrawningLocomotive?>? comparer = null)
{
// проверка позиции
// проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда, если нет после, ищем до
// вставка
if (position >= Count || position < 0)
{
return -1;
}
if (_collection.Contains(obj, comparer)) throw new AlreadyExistingObject(obj.GetDataForSave());
if (_collection[position] == null)
{
@ -146,4 +145,14 @@ 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

@ -18,12 +18,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>
/// Ключевое слово, с которого должен начинаться файл
@ -45,7 +45,7 @@ public class StorageCollection<T>
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@ -57,14 +57,15 @@ public class StorageCollection<T>
{
// проверка что name не пустой и нет в словаре записи с таким ключом
// логика добавления
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name) || collectionType == CollectionType.None) return;
CollectionInfo collectionInfo = new(name, collectionType, string.Empty);
if (string.IsNullOrEmpty(collectionInfo.Name) || _storages.ContainsKey(collectionInfo)) return;
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>();
}
}
@ -75,10 +76,9 @@ public class StorageCollection<T>
/// <param name="name">Имя коллекции</param>
public void DelCollection(string name)
{
if (_storages.ContainsKey(name))
{
_storages.Remove(name);
}
var obj = new CollectionInfo(name, CollectionType.None, string.Empty);
if (!_storages.ContainsKey(obj)) return;
_storages.Remove(obj);
}
public ICollectionGenericObjects<T>? this[int index]
@ -113,9 +113,9 @@ public class StorageCollection<T>
using (StreamWriter writer = new StreamWriter(filename))
{
writer.WriteLine(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
writer.Write($"{value.Key}{_separatorForKeyValue}{value.Value.GetCollectionType}{_separatorForKeyValue}{value.Value.MaxCount}{_separatorForKeyValue}");
writer.Write($"{value.Key}{_separatorForKeyValue}{value.Value.MaxCount}{_separatorForKeyValue}");
writer.Write(_separatorItems);
foreach (T? item in value.Value.GetItems())
@ -158,21 +158,22 @@ public class StorageCollection<T>
{
string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
if (record.Length != 3)
{
line = reader.ReadLine();
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType);
if (collection == null) throw new NullCollectionExpection("Не удалось создать коллекцию"); ;
collection.MaxCount = Convert.ToInt32(record[2]);
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
@ -180,7 +181,7 @@ public class StorageCollection<T>
{
try
{
collection.Insert(locomotive);
collection.Insert(locomotive, new DrawningLocomotiveEqutables());
}
catch(Exception ex)
{
@ -188,7 +189,7 @@ public class StorageCollection<T>
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
line = reader.ReadLine();
}

View File

@ -0,0 +1,45 @@
using ProjectElectricLocomotive.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Drawnings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningLocomotiveCompareByColor : IComparer<DrawningLocomotive?>
{
public int Compare(DrawningLocomotive? x, DrawningLocomotive? y)
{
if (x == null && y == null) return 0;
if (x == null || x.EntityLocomotive == null) return -1;
if (y == null || y.EntityLocomotive == null) return 1;
if (x.GetType().Name != y.GetType().Name) return -1;
var colorCompare = x.EntityLocomotive.BodyColor.ToArgb().CompareTo(y.EntityLocomotive.BodyColor.ToArgb());
if (colorCompare != 0)
{
return colorCompare;
}
if (x is DrawningElectricLocomotive && y is DrawningElectricLocomotive)
{
colorCompare = ((EntityElectricLocomotive)x.EntityLocomotive).AdditionalColor.ToArgb().CompareTo(((EntityElectricLocomotive)y.EntityLocomotive).AdditionalColor.ToArgb());
if (colorCompare != 0)
{
return colorCompare;
}
}
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,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Drawnings;
/// <summary>
/// Сравнение по типу, скорости, весу
/// </summary>
public class DrawningLocomotiveCompareByType : IComparer<DrawningLocomotive?>
{
public int Compare(DrawningLocomotive? x, DrawningLocomotive? y)
{
if (x == null && y == null) return 0;
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,34 @@
using ProjectElectricLocomotive.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.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 DrawningElectricLocomotive && y is DrawningElectricLocomotive)
{
if (((EntityElectricLocomotive)x.EntityLocomotive).AdditionalColor != ((EntityElectricLocomotive)y.EntityLocomotive).AdditionalColor) return false;
Review

Зачем неоднократные преобразования, что мешает сделать это один раз?

Зачем неоднократные преобразования, что мешает сделать это один раз?
if (((EntityElectricLocomotive)x.EntityLocomotive).ElectricHorns != ((EntityElectricLocomotive)y.EntityLocomotive).ElectricHorns) return false;
if (((EntityElectricLocomotive)x.EntityLocomotive).BatteryPlacement != ((EntityElectricLocomotive)y.EntityLocomotive).BatteryPlacement) return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawningLocomotive obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Exceptions;
/// <summary>
/// Класс, описывающий переполнение коллекции
/// </summary>
[Serializable]
internal class AlreadyExistingObject : ApplicationException
{
public AlreadyExistingObject(string objName) : base("Данный объект уже существует " + objName) { }
public AlreadyExistingObject() : base() { }
public AlreadyExistingObject(string message, Exception exception) : base(message, exception) { }
public AlreadyExistingObject(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -53,6 +53,8 @@
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@ -69,7 +71,7 @@
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(640, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(200, 569);
groupBoxTools.Size = new Size(200, 678);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -98,6 +100,8 @@
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddLocomotive);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
@ -105,9 +109,9 @@
panelCompanyTools.Controls.Add(buttonRemoveLocomotive);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 340);
panelCompanyTools.Location = new Point(3, 364);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(194, 226);
panelCompanyTools.Size = new Size(194, 311);
panelCompanyTools.TabIndex = 8;
//
// buttonAddLocomotive
@ -246,7 +250,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(640, 569);
pictureBox.Size = new Size(640, 678);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -290,11 +294,31 @@
//
openFileDialog.Filter = "txt file|*.txt";
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(3, 260);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(188, 31);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Location = new Point(3, 223);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(188, 31);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// FormLocomotiveCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(840, 593);
ClientSize = new Size(840, 702);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@ -340,5 +364,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -78,19 +78,19 @@ public partial class FormLocomotiveCollection : Form
try
{
if((_company + locomotive) != -1)
if ((_company + locomotive) != -1)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation("Добавлен объект: {entity}", locomotive.GetDataForSave());
pictureBox.Image = _company.Show();
}
}
catch(Exception ex)
catch (Exception ex)
{
MessageBox.Show("Объект не был добавлен");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -228,11 +228,11 @@ public partial class FormLocomotiveCollection : Form
private void RefreshListBoxItems()
{
listBoxCollection.Items.Clear();
foreach(string colName in _storageCollection.Keys)
foreach (var colName in _storageCollection.Keys)
{
if (!string.IsNullOrEmpty(colName))
if (!string.IsNullOrEmpty(colName.Name))
{
listBoxCollection.Items.Add(colName);
listBoxCollection.Items.Add(colName.Name);
}
}
}
@ -284,7 +284,7 @@ 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);
@ -307,7 +307,7 @@ public partial class FormLocomotiveCollection : Form
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка прошла успешно из файла, {filename}", openFileDialog.FileName);
}
catch(Exception ex)
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка {Message}", ex.Message);
@ -315,4 +315,36 @@ public partial class FormLocomotiveCollection : Form
RefreshListBoxItems();
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareCars(new DrawningLocomotiveCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareCars(new DrawningLocomotiveCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareCars(IComparer<DrawningLocomotive?> comparer)
{
if (_company == null) return;
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}