This commit is contained in:
Anastasia Yazykova 2024-06-10 03:49:04 +04:00
parent d4da4c02ae
commit 2d339f7d20
13 changed files with 472 additions and 85 deletions

View File

@ -55,7 +55,7 @@ private int GetMaxCount => _pictureWidth / _placeSizeWidth * (_pictureHeight / _
/// <returns></returns> /// <returns></returns>
public static int operator +(AbstractCompany company, DrawningBus bus) public static int operator +(AbstractCompany company, DrawningBus bus)
{ {
return company._collection.Insert(bus); return company._collection.Insert(bus,new DrawiningBusEqutables());
} }
/// <summary> /// <summary>
/// Перегрузка оператора удаления для класса /// Перегрузка оператора удаления для класса
@ -102,4 +102,5 @@ private int GetMaxCount => _pictureWidth / _placeSizeWidth * (_pictureHeight / _
/// Расстановка объектов /// Расстановка объектов
/// </summary> /// </summary>
protected abstract void SetObjectsPosition(); protected abstract void SetObjectsPosition();
public void Sort(IComparer<DrawningBus?> comparer) => _collection?.CollectionSort(comparer);
} }

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TrolleybusProject.Drawnings;
namespace TrolleybusProject.CollectionGenericObjects;
public class DrawningBusCompareByType : IComparer<DrawningBus?>
{
public int Compare(DrawningBus? x, DrawningBus? y)
{
if (x == null && y == null) return 0;
if (x == null || x.EntityBus == null)
{
return -1;
}
if (y == null || y.EntityBus == null)
{
return 1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight);
}
}

View File

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

View File

@ -1,8 +1,10 @@
using System; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using TrolleybusProject.Drawnings;
using TrolleybusProject.Exceptions; using TrolleybusProject.Exceptions;
namespace TrolleybusProject.CollectionGenericObjects; namespace TrolleybusProject.CollectionGenericObjects;
@ -48,27 +50,48 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{ {
if (Count + 1 > _maxCount) if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (comparer != null)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
}
}
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (Count == _maxCount)
{ {
throw new CollectionOverflowException(Count); throw new CollectionOverflowException(Count);
} }
_collection.Add(obj); if (position >= Count || position < 0)
return 1;
}
public int Insert(T obj, int position)
{
if (position < 0 || position > Count)
{ {
throw new PositionOutOfCollectionException(position); throw new PositionOutOfCollectionException(position);
} }
if (Count + 1 > _maxCount)
if (comparer != null)
{ {
throw new CollectionOverflowException(Count); for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
} }
}
}
_collection.Insert(position, obj); _collection.Insert(position, obj);
return 1; return position;
} }
public T? Remove(int position) public T? Remove(int position)
{ {
@ -89,6 +112,10 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
} }
} }
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
} }

View File

@ -3,8 +3,10 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using TrolleybusProject.Drawnings;
using TrolleybusProject.Exceptions; using TrolleybusProject.Exceptions;
namespace TrolleybusProject.CollectionGenericObjects; namespace TrolleybusProject.CollectionGenericObjects;
internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T> internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
@ -51,13 +53,26 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
}
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{ {
if (comparer != null)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
}
}
for (int i = 0; i < Count; i++) for (int i = 0; i < Count; i++)
{ {
if (_collection[i] == null) if (_collection[i] == null)
@ -66,12 +81,27 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i; return i;
} }
} }
throw new CollectionOverflowException(Count); throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{ {
if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
}
if (comparer != null)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
}
}
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) if (_collection[position] == null)
{ {
@ -117,4 +147,13 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
public void CollectionSort(IComparer<T?> comparer)
{
List<T?> value = new List<T?>(_collection);
value.Sort(comparer);
value.CopyTo(_collection, 0);
}
} }

View File

@ -1,4 +1,5 @@
using System; using ProjectTrolleybus.Exceptions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -15,12 +16,12 @@ public class StorageCollection<T>
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages; readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary> /// <summary>
/// Возвращение списка названий коллекций /// Возвращение списка названий коллекций
/// </summary> /// </summary>
public List<string> Keys => _storages.Keys.ToList(); public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary> /// <summary>
/// Ключевое слово, с которого должен начинаться файл /// Ключевое слово, с которого должен начинаться файл
@ -42,7 +43,7 @@ public class StorageCollection<T>
/// ///
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
} }
/// <summary> /// <summary>
/// Добавление коллекции в хранилище /// Добавление коллекции в хранилище
@ -51,28 +52,35 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param> /// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(string name, CollectionType collectionType)
{ {
if (_storages.ContainsKey(name) && name == "") CollectionInfo collectionInfo = new(name, collectionType, string.Empty);
{ if (name == null || _storages.ContainsKey(collectionInfo))
return; return;
switch (collectionType)
{
case CollectionType.None:
return;
case CollectionType.Massive:
_storages[collectionInfo] = new MassiveGenericObjects<T>();
return;
case CollectionType.List:
_storages[collectionInfo] = new ListGenericObjects<T>();
return;
default:
break;
} }
if (collectionType == CollectionType.Massive)
{
_storages[name] = new MassiveGenericObjects<T>();
} }
else
{
_storages[name] = new ListGenericObjects<T>();
}
}
/// <summary> /// <summary>
/// Удаление коллекции /// Удаление коллекции
/// </summary> /// </summary>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
public void DelCollection(string name) public void DelCollection(string name)
{ {
_storages.Remove(name); CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{
_storages.Remove(collectionInfo);
}
} }
/// <summary> /// <summary>
/// Доступ к коллекции /// Доступ к коллекции
@ -83,11 +91,12 @@ public class StorageCollection<T>
{ {
get get
{ {
if (name == "") CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{ {
return null; return _storages[collectionInfo];
} }
return _storages[name]; return null;
} }
} }
@ -102,10 +111,13 @@ public class StorageCollection<T>
{ {
File.Delete(filename); File.Delete(filename);
} }
using (StreamWriter writer = new(filename)) using (StreamWriter writer = new(filename))
{ {
writer.Write(_collectionKey); writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages) foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{ {
writer.Write(Environment.NewLine); writer.Write(Environment.NewLine);
// не сохраняем пустые коллекции // не сохраняем пустые коллекции
@ -141,42 +153,42 @@ public class StorageCollection<T>
{ {
throw new FileNotFoundException("Файл не существует!"); throw new FileNotFoundException("Файл не существует!");
} }
using (StreamReader reader = new(filename))
using (StreamReader sr = new(filename))
{ {
string line = reader.ReadLine(); string? line = sr.ReadLine();
if (line == null || line.Length == 0) if (line == null || line.Length == 0)
{ {
throw new ArgumentException("В файле нет данных"); throw new ArgumentException("В файле нет данных");
} }
if (!line.Equals(_collectionKey))
if (line != _collectionKey)
{ {
throw new InvalidDataException("В файле неверные данные"); throw new InvalidDataException("В файле неверные данные");
} }
_storages.Clear(); _storages.Clear();
while ((line = reader.ReadLine()) != null)
while ((line = sr.ReadLine()) != null)
{ {
string[] record = line.Split(_separatorForKeyValue, string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4) if (record.Length != 3)
{ {
continue; continue;
} }
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? throw new ArgumentNullException("Не удалось определить тип коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ?? throw new ArgumentNullException("Не удалось создать коллекцию");
if (collection == null) collection.MaxCount = Convert.ToInt32(record[1]);
{ string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
throw new InvalidCastException("Не удалось определить тип коллекции: " + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningBus() is T boat) if (elem?.CreateDrawningBus() is T bus)
{ {
try try
{ {
if (collection.Insert(boat) < 0) if (collection.Insert(bus) < 0)
{ {
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
@ -189,10 +201,9 @@ public class StorageCollection<T>
} }
} }
_storages.Add(record[0], collection); _storages.Add(collectionInfo, collection);
} }
} }
} }
/// <summary> /// <summary>

View File

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

@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TrolleybusProject.Entities;
namespace TrolleybusProject.Drawnings;
internal class DrawiningBusEqutables: IEqualityComparer<DrawningBus?>
{
public bool Equals(DrawningBus? x, DrawningBus? y)
{
if (x == null || x.EntityBus == null)
{
return false;
}
if (y == null || y.EntityBus == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityBus.Speed != y.EntityBus.Speed)
{
return false;
}
if (x.EntityBus.Weight != y.EntityBus.Weight)
{
return false;
}
if (x.EntityBus.BodyColor != y.EntityBus.BodyColor)
{
return false;
}
if (x is DrawningTrolleybus && y is DrawningTrolleybus)
{
if (((EntityTrolleybus)x.EntityBus).AdditionalColor !=
((EntityTrolleybus)y.EntityBus).AdditionalColor)
{
return false;
}
if (((EntityTrolleybus)x.EntityBus).Roga !=
((EntityTrolleybus)y.EntityBus).Roga)
{
return false;
}
if (((EntityTrolleybus)x.EntityBus).Otsek !=
((EntityTrolleybus)y.EntityBus).Otsek)
{
return false;
}
if (((EntityTrolleybus)x.EntityBus).Doors !=
((EntityTrolleybus)y.EntityBus).Doors)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningBus obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TrolleybusProject.Drawnings;
public class DrawningBusCompareByColor: IComparer<DrawningBus?>
{
public int Compare(DrawningBus? x, DrawningBus? y)
{
if (x == null || x.EntityBus == null)
{
return 1;
}
if (y == null || y.EntityBus == null)
{
return -1;
}
var bodycolorCompare = x.EntityBus.BodyColor.Name.CompareTo(y.EntityBus.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight);
}
}

View File

@ -0,0 +1,14 @@
using System.Runtime.Serialization;
using TrolleybusProject;
namespace ProjectTrolleybus.Exceptions;
public class CollectionAlreadyExistsException : Exception
{
public CollectionAlreadyExistsException() : base() { }
public CollectionAlreadyExistsException(CollectionInfo collectioninfo) : base($"Коллекция {collectioninfo} уже существует!") { }
public CollectionAlreadyExistsException(string name, Exception exception) :
base($"Коллекция {name} уже существует!", exception)
{ }
protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
public class CollectionInsertException : Exception
{
public CollectionInsertException(object obj) : base($"Объект {obj} повторяется") { }
public CollectionInsertException() : base() { }
public CollectionInsertException(string message) : base(message) { }
public CollectionInsertException(string message, Exception exception) :
base(message, exception)
{ }
protected CollectionInsertException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -55,6 +55,8 @@
LoadToolStripMenuItem = new ToolStripMenuItem(); LoadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog(); saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog(); openFileDialog = new OpenFileDialog();
buttonByType = new Button();
ByColor = new Button();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
@ -71,7 +73,7 @@
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(904, 33); groupBoxTools.Location = new Point(904, 33);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(300, 623); groupBoxTools.Size = new Size(300, 702);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
@ -88,7 +90,9 @@
// //
// panelCompanyTools // panelCompanyTools
// //
panelCompanyTools.Controls.Add(buttonByType);
panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(ByColor);
panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonAddBus); panelCompanyTools.Controls.Add(buttonAddBus);
panelCompanyTools.Controls.Add(buttonDelTrolleybus); panelCompanyTools.Controls.Add(buttonDelTrolleybus);
@ -96,7 +100,7 @@
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(0, 397); panelCompanyTools.Location = new Point(0, 397);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(294, 259); panelCompanyTools.Size = new Size(294, 305);
panelCompanyTools.TabIndex = 9; panelCompanyTools.TabIndex = 9;
// //
// buttonRefresh // buttonRefresh
@ -250,7 +254,7 @@
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 33); pictureBox.Location = new Point(0, 33);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(904, 623); pictureBox.Size = new Size(904, 702);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
@ -314,11 +318,33 @@
// //
openFileDialog.Filter = "txt file | *.txt"; openFileDialog.Filter = "txt file | *.txt";
// //
// buttonByType
//
buttonByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonByType.Location = new Point(6, 259);
buttonByType.Name = "buttonByType";
buttonByType.Size = new Size(268, 34);
buttonByType.TabIndex = 8;
buttonByType.Text = "Сравнить по типу";
buttonByType.UseVisualStyleBackColor = true;
buttonByType.Click += button1_Click;
//
// ByColor
//
ByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
ByColor.Location = new Point(23, 215);
ByColor.Name = "ByColor";
ByColor.Size = new Size(247, 38);
ByColor.TabIndex = 7;
ByColor.Text = "Сравнить по цвету";
ByColor.UseVisualStyleBackColor = true;
ByColor.Click += ByColor_Click;
//
// FormBusCollection // FormBusCollection
// //
AutoScaleDimensions = new SizeF(10F, 25F); AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1204, 656); ClientSize = new Size(1204, 735);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip); Controls.Add(menuStrip);
@ -366,5 +392,7 @@
private ToolStripMenuItem файлToolStripMenuItem; private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem save_ToolStripMenuItem; private ToolStripMenuItem save_ToolStripMenuItem;
private ToolStripMenuItem load_ToolStripMenuItem; private ToolStripMenuItem load_ToolStripMenuItem;
private Button buttonByType;
private Button ByColor;
} }
} }

View File

@ -44,25 +44,27 @@ public partial class FormBusCollection : Form
form.AddEvent(SetBus); form.AddEvent(SetBus);
} }
private void SetBus(DrawningBus bus) private void SetBus(DrawningBus bus)
{
try
{ {
if (_company == null || bus == null) if (_company == null || bus == null)
{ {
return; return;
} }
if (_company + bus != -1) try
{ {
int addingObject = (_company + bus);
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект {bus.GetDataForSave()}");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: {0}", bus.GetDataForSave());
}
} }
catch (CollectionOverflowException ex) catch (CollectionOverflowException ex)
{ {
MessageBox.Show(ex.Message); MessageBox.Show("Не удалось добавить объект");
_logger.LogError($"Ошибка: {ex.Message}"); _logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
catch (CollectionInsertException)
{
MessageBox.Show("Такой объект уже существует");
_logger.LogError("Ошибка:обьект повторяется {0}", bus);
} }
} }
@ -184,7 +186,7 @@ public partial class FormBusCollection : Form
listBoxCollection.Items.Clear(); listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i) for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{ {
string? colName = _storageCollection.Keys?[i]; string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName)) if (!string.IsNullOrEmpty(colName))
{ {
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(colName);
@ -281,6 +283,31 @@ public partial class FormBusCollection : Form
} }
private void button1_Click(object sender, EventArgs e)
{
CompareBus(new DrawningBusCompareByType());
}
private void ByColor_Click(object sender, EventArgs e)
{
CompareBus(new DrawningBusCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareBus(IComparer<DrawningBus?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
} }