This commit is contained in:
Roman-Klemendeev 2024-06-09 23:19:22 +04:00
parent e25dcc5567
commit 55723d34bc
13 changed files with 337 additions and 54 deletions

View File

@ -59,7 +59,7 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningTanker tanker)
{
return company._collection?.Insert(tanker) ?? -1;
return company._collection?.Insert(tanker, new DrawningTankerEqutables()) ?? -1;
}
/// <summary>
@ -118,4 +118,10 @@ public abstract class AbstractCompany
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningTanker?> comparer) => _collection?.CollectionSort(comparer);
}

View File

@ -0,0 +1,44 @@

namespace ProjectGasolineTanker.CollectionGenericObjects;
public class CollectionInfo : IEquatable<CollectionInfo>
{
public string Name { get; private set; }
public CollectionType CollectionType { get; private set; }
public string Description { get; private set; }
private static readonly string _separator = "-";
public CollectionInfo(string name, CollectionType collectionType, string description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
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

@ -18,7 +18,7 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
@ -26,7 +26,7 @@ public interface ICollectionGenericObjects<T>
/// <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?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
@ -52,4 +52,9 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}

View File

@ -37,15 +37,29 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
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?>? comparer = null)
{
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectIsEqualException();
}
}
if (position < 0 || position >= Count)
throw new PositionOutOfCollectionException(position);
@ -71,4 +85,8 @@ 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 ProjectGasolineTanker.Exceptions;
using ProjectGasolineTanker.Drawnings;
using ProjectGasolineTanker.Exceptions;
namespace ProjectGasolineTanker.CollectionGenericObjects;
@ -51,8 +52,16 @@ where T : class
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?> comparer = null)
{
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningTanker>).Equals(obj as DrawningTanker, item as DrawningTanker))
throw new ObjectIsEqualException();
}
}
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
@ -64,8 +73,16 @@ where T : class
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningTanker>).Equals(obj as DrawningTanker, item as DrawningTanker))
throw new ObjectIsEqualException();
}
}
if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
@ -115,4 +132,9 @@ where T : class
yield return _collection[i];
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -9,12 +9,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>
/// Ключевое слово, с которого должен начинаться файл
@ -36,7 +36,7 @@ public class StorageCollection<T>
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@ -46,17 +46,18 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name))
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{
return;
}
switch (collectionType)
{
case CollectionType.Massive:
_storages[name] = new MassiveGenericObjects<T>();
_storages[collectionInfo] = new MassiveGenericObjects<T>();
break;
case CollectionType.List:
_storages[name] = new ListGenericObjects<T>();
_storages[collectionInfo] = new ListGenericObjects<T>();
break;
default:
return;
@ -69,9 +70,10 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
if (_storages.ContainsKey(name))
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{
_storages.Remove(name);
_storages.Remove(collectionInfo);
}
}
@ -85,10 +87,9 @@ public class StorageCollection<T>
{
get
{
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;
}
}
@ -115,15 +116,13 @@ public class StorageCollection<T>
using (StreamWriter sw = new StreamWriter(filename))
{
sw.WriteLine(_collectionKey.ToString());
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> kvpair in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> kvpair in _storages)
{
// не сохраняем пустые коллекции
if (kvpair.Value.Count == 0)
continue;
sb.Append(kvpair.Key);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in kvpair.Value.GetItems())
@ -158,34 +157,37 @@ public class StorageCollection<T>
str = sr.ReadLine();
if (str == null || str.Length == 0)
throw new Exception("В файле нет данных");
if (str != _collectionKey.ToString())
if (!str.StartsWith(_collectionKey))
throw new Exception("В файле неверные данные");
_storages.Clear();
while ((str = sr.ReadLine()) != null)
string strs = "";
while ((strs = sr.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);
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось создать коллекцию");
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?.CreateDrawningTanker() is T tanker)
if (elem?.CreateDrawningTanker() is T tank)
{
try
{
if (collection.Insert(tanker) == -1)
if (collection.Insert(tank) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
@ -193,7 +195,7 @@ public class StorageCollection<T>
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}

View File

@ -0,0 +1,29 @@

namespace ProjectGasolineTanker.Drawnings;
public class DrawningTankerCompareByColor : IComparer<DrawningTanker?>
{
public int Compare(DrawningTanker? x, DrawningTanker? y)
{
if (x == null || x.EntityTanker == null)
{
return 1;
}
if (y == null || y.EntityTanker == null)
{
return -1;
}
var bodycolorCompare = x.EntityTanker.BodyColor.Name.CompareTo(y.EntityTanker.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityTanker.Speed.CompareTo(y.EntityTanker.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTanker.Weight.CompareTo(y.EntityTanker.Weight);
}
}

View File

@ -0,0 +1,30 @@

namespace ProjectGasolineTanker.Drawnings;
public class DrawningTankerCompareByType : IComparer<DrawningTanker?>
{
public int Compare(DrawningTanker? x, DrawningTanker? y)
{
if (x == null || x.EntityTanker == null)
{
return 1;
}
if (y == null || y.EntityTanker == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityTanker.Speed.CompareTo(y.EntityTanker.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTanker.Weight.CompareTo(y.EntityTanker.Weight);
}
}

View File

@ -0,0 +1,56 @@
using ProjectGasolineTanker.Entities;
using System.Diagnostics.CodeAnalysis;
namespace ProjectGasolineTanker.Drawnings;
public class DrawningTankerEqutables : IEqualityComparer<DrawningTanker>
{
public bool Equals(DrawningTanker? x, DrawningTanker? y)
{
if (x == null || x.EntityTanker == null)
{
return false;
}
if (y == null || y.EntityTanker == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTanker.Speed != y.EntityTanker.Speed)
{
return false;
}
if (x.EntityTanker.Weight != y.EntityTanker.Weight)
{
return false;
}
if (x.EntityTanker.BodyColor != y.EntityTanker.BodyColor)
{
return false;
}
if (x is DrawningGasolineTanker && y is DrawningGasolineTanker)
{
EntityGasolineTanker _x = (EntityGasolineTanker)x.EntityTanker;
EntityGasolineTanker _y = (EntityGasolineTanker)x.EntityTanker;
if (_x.AdditionalColor != _y.AdditionalColor)
{
return false;
}
if (_x.Tank != _y.Tank)
{
return false;
}
if (_x.Signalbeacon != _y.Signalbeacon)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningTanker obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,18 @@

using System.Runtime.Serialization;
namespace ProjectGasolineTanker.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

@ -54,6 +54,8 @@ namespace ProjectGasolineTanker
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonSortByType = new Button();
buttonByColor = new Button();
Инструменты.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@ -70,13 +72,15 @@ namespace ProjectGasolineTanker
Инструменты.Dock = DockStyle.Right;
Инструменты.Location = new Point(861, 24);
Инструменты.Name = "Инструменты";
Инструменты.Size = new Size(225, 627);
Инструменты.Size = new Size(225, 650);
Инструменты.TabIndex = 0;
Инструменты.TabStop = false;
Инструменты.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddTanker);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonGoToCheck);
@ -85,15 +89,15 @@ namespace ProjectGasolineTanker
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Location = new Point(3, 380);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(219, 244);
panelCompanyTools.Size = new Size(219, 267);
panelCompanyTools.TabIndex = 8;
//
// buttonAddTanker
//
buttonAddTanker.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddTanker.Location = new Point(3, 21);
buttonAddTanker.Location = new Point(0, 0);
buttonAddTanker.Name = "buttonAddTanker";
buttonAddTanker.Size = new Size(213, 37);
buttonAddTanker.Size = new Size(216, 48);
buttonAddTanker.TabIndex = 1;
buttonAddTanker.Text = "Добавление грузовика";
buttonAddTanker.UseVisualStyleBackColor = true;
@ -101,7 +105,7 @@ namespace ProjectGasolineTanker
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(3, 86);
maskedTextBoxPosition.Location = new Point(3, 54);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(213, 23);
@ -111,9 +115,9 @@ namespace ProjectGasolineTanker
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 161);
buttonGoToCheck.Location = new Point(3, 119);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(213, 40);
buttonGoToCheck.Size = new Size(213, 30);
buttonGoToCheck.TabIndex = 6;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
@ -122,9 +126,9 @@ namespace ProjectGasolineTanker
// buttonRemoveTanker
//
buttonRemoveTanker.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveTanker.Location = new Point(3, 115);
buttonRemoveTanker.Location = new Point(3, 83);
buttonRemoveTanker.Name = "buttonRemoveTanker";
buttonRemoveTanker.Size = new Size(213, 40);
buttonRemoveTanker.Size = new Size(213, 30);
buttonRemoveTanker.TabIndex = 4;
buttonRemoveTanker.Text = "Удаление автомобиль";
buttonRemoveTanker.UseVisualStyleBackColor = true;
@ -133,9 +137,9 @@ namespace ProjectGasolineTanker
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(3, 207);
buttonRefresh.Location = new Point(0, 155);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(213, 40);
buttonRefresh.Size = new Size(216, 28);
buttonRefresh.TabIndex = 5;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
@ -250,7 +254,7 @@ namespace ProjectGasolineTanker
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(861, 627);
pictureBox.Size = new Size(861, 650);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -294,12 +298,35 @@ namespace ProjectGasolineTanker
//
openFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(3, 189);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(213, 29);
buttonSortByType.TabIndex = 8;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonByColor
//
buttonByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonByColor.Font = new Font("Segoe UI", 8.25F, FontStyle.Regular, GraphicsUnit.Point);
buttonByColor.Location = new Point(3, 224);
buttonByColor.Name = "buttonByColor";
buttonByColor.Size = new Size(213, 29);
buttonByColor.TabIndex = 9;
buttonByColor.Text = "Сортировка по цвету";
buttonByColor.UseVisualStyleBackColor = true;
buttonByColor.Click += buttonByColor_Click;
//
// FormTankerCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
AutoScroll = true;
ClientSize = new Size(1086, 651);
ClientSize = new Size(1086, 674);
Controls.Add(pictureBox);
Controls.Add(Инструменты);
Controls.Add(menuStrip);
@ -344,5 +371,7 @@ namespace ProjectGasolineTanker
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonByColor;
private Button buttonSortByType;
}
}

View File

@ -80,6 +80,11 @@ public partial class FormTankerCollection : Form
MessageBox.Show("В коллекции превышено допустимое количество элементов");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ObjectIsEqualException ex)
{
MessageBox.Show("Такой объект уже существует в коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
/// Удаление объекта
@ -210,7 +215,7 @@ public partial class FormTankerCollection : 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);
@ -319,5 +324,24 @@ public partial class FormTankerCollection : Form
}
}
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareTanker(new DrawningTankerCompareByType());
}
private void buttonByColor_Click(object sender, EventArgs e)
{
CompareTanker(new DrawningTankerCompareByColor());
}
private void CompareTanker(IComparer<DrawningTanker?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}

View File

@ -165,9 +165,9 @@
checkBoxSignalbeacon.AutoSize = true;
checkBoxSignalbeacon.Location = new Point(12, 168);
checkBoxSignalbeacon.Name = "checkBoxSignalbeacon";
checkBoxSignalbeacon.Size = new Size(232, 34);
checkBoxSignalbeacon.Size = new Size(151, 19);
checkBoxSignalbeacon.TabIndex = 9;
checkBoxSignalbeacon.Text = "Признак наличия сигнального маяка\r\n\r\n";
checkBoxSignalbeacon.Text = "Признак наличия бака";
checkBoxSignalbeacon.UseVisualStyleBackColor = true;
//
// checkBoxTanker
@ -175,9 +175,9 @@
checkBoxTanker.AutoSize = true;
checkBoxTanker.Location = new Point(12, 125);
checkBoxTanker.Name = "checkBoxTanker";
checkBoxTanker.Size = new Size(154, 19);
checkBoxTanker.Size = new Size(235, 19);
checkBoxTanker.TabIndex = 8;
checkBoxTanker.Text = "Признак наличия бака \r\n";
checkBoxTanker.Text = "Признак наличия сигнального маяка \r\n";
checkBoxTanker.UseVisualStyleBackColor = true;
//
// numericUpDownWeight