Лабораторная №8

This commit is contained in:
yuliya.mavrina@internet.ru 2023-12-26 10:32:41 +03:00
parent 2fbd29e672
commit a3ddbf0952
10 changed files with 294 additions and 88 deletions

View File

@ -34,6 +34,8 @@
maskedTextBoxNumber = new MaskedTextBox(); maskedTextBoxNumber = new MaskedTextBox();
pictureBoxCollection = new PictureBox(); pictureBoxCollection = new PictureBox();
panel = new Panel(); panel = new Panel();
ButtonSortByColor = new Button();
ButtonSortByType = new Button();
textBoxStorageName = new TextBox(); textBoxStorageName = new TextBox();
listBoxStorages = new ListBox(); listBoxStorages = new ListBox();
ButtonDelObject = new Button(); ButtonDelObject = new Button();
@ -41,10 +43,9 @@
menuStrip = new MenuStrip(); menuStrip = new MenuStrip();
ToolStripMenuItem = new ToolStripMenuItem(); ToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem(); LoadToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem(); SaveToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog(); openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog(); saveFileDialog = new SaveFileDialog();
SaveToolStripMenuItem = new ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
panel.SuspendLayout(); panel.SuspendLayout();
menuStrip.SuspendLayout(); menuStrip.SuspendLayout();
@ -53,7 +54,7 @@
// buttonAddBus // buttonAddBus
// //
buttonAddBus.Anchor = AnchorStyles.Top | AnchorStyles.Right; buttonAddBus.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonAddBus.Location = new Point(19, 277); buttonAddBus.Location = new Point(19, 287);
buttonAddBus.Name = "buttonAddBus"; buttonAddBus.Name = "buttonAddBus";
buttonAddBus.Size = new Size(138, 31); buttonAddBus.Size = new Size(138, 31);
buttonAddBus.TabIndex = 0; buttonAddBus.TabIndex = 0;
@ -64,7 +65,7 @@
// buttonRemoveBus // buttonRemoveBus
// //
buttonRemoveBus.Anchor = AnchorStyles.Top | AnchorStyles.Right; buttonRemoveBus.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonRemoveBus.Location = new Point(19, 343); buttonRemoveBus.Location = new Point(19, 353);
buttonRemoveBus.Name = "buttonRemoveBus"; buttonRemoveBus.Name = "buttonRemoveBus";
buttonRemoveBus.Size = new Size(138, 31); buttonRemoveBus.Size = new Size(138, 31);
buttonRemoveBus.TabIndex = 1; buttonRemoveBus.TabIndex = 1;
@ -86,7 +87,7 @@
// maskedTextBoxNumber // maskedTextBoxNumber
// //
maskedTextBoxNumber.Anchor = AnchorStyles.Top | AnchorStyles.Right; maskedTextBoxNumber.Anchor = AnchorStyles.Top | AnchorStyles.Right;
maskedTextBoxNumber.Location = new Point(36, 314); maskedTextBoxNumber.Location = new Point(36, 324);
maskedTextBoxNumber.Name = "maskedTextBoxNumber"; maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(100, 23); maskedTextBoxNumber.Size = new Size(100, 23);
maskedTextBoxNumber.TabIndex = 3; maskedTextBoxNumber.TabIndex = 3;
@ -103,6 +104,8 @@
// panel // panel
// //
panel.Anchor = AnchorStyles.Top | AnchorStyles.Right; panel.Anchor = AnchorStyles.Top | AnchorStyles.Right;
panel.Controls.Add(ButtonSortByColor);
panel.Controls.Add(ButtonSortByType);
panel.Controls.Add(textBoxStorageName); panel.Controls.Add(textBoxStorageName);
panel.Controls.Add(listBoxStorages); panel.Controls.Add(listBoxStorages);
panel.Controls.Add(ButtonDelObject); panel.Controls.Add(ButtonDelObject);
@ -118,6 +121,26 @@
panel.TabIndex = 5; panel.TabIndex = 5;
panel.Tag = ""; panel.Tag = "";
// //
// ButtonSortByColor
//
ButtonSortByColor.Location = new Point(13, 247);
ButtonSortByColor.Name = "ButtonSortByColor";
ButtonSortByColor.Size = new Size(138, 25);
ButtonSortByColor.TabIndex = 12;
ButtonSortByColor.Text = "Сортировка по цвету";
ButtonSortByColor.UseVisualStyleBackColor = true;
ButtonSortByColor.Click += ButtonSortByColor_Click;
//
// ButtonSortByType
//
ButtonSortByType.Location = new Point(13, 214);
ButtonSortByType.Name = "ButtonSortByType";
ButtonSortByType.Size = new Size(138, 27);
ButtonSortByType.TabIndex = 11;
ButtonSortByType.Text = "Сортировка по типу";
ButtonSortByType.UseVisualStyleBackColor = true;
ButtonSortByType.Click += ButtonSortByType_Click;
//
// textBoxStorageName // textBoxStorageName
// //
textBoxStorageName.Location = new Point(13, 36); textBoxStorageName.Location = new Point(13, 36);
@ -129,9 +152,9 @@
// //
listBoxStorages.FormattingEnabled = true; listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 15; listBoxStorages.ItemHeight = 15;
listBoxStorages.Location = new Point(13, 100); listBoxStorages.Location = new Point(3, 100);
listBoxStorages.Name = "listBoxStorages"; listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(138, 64); listBoxStorages.Size = new Size(165, 64);
listBoxStorages.TabIndex = 8; listBoxStorages.TabIndex = 8;
listBoxStorages.SelectedIndexChanged += listBoxStorages_SelectedIndexChanged; listBoxStorages.SelectedIndexChanged += listBoxStorages_SelectedIndexChanged;
// //
@ -174,16 +197,16 @@
// LoadToolStripMenuItem // LoadToolStripMenuItem
// //
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem"; LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(180, 22); LoadToolStripMenuItem.Size = new Size(133, 22);
LoadToolStripMenuItem.Text = "Загрузить"; LoadToolStripMenuItem.Text = "Загрузить";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
// //
// saveToolStripMenuItem // SaveToolStripMenuItem
// //
saveToolStripMenuItem.Name = "saveToolStripMenuItem"; SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
saveToolStripMenuItem.Size = new Size(180, 22); SaveToolStripMenuItem.Size = new Size(133, 22);
saveToolStripMenuItem.Text = "Сохранить"; SaveToolStripMenuItem.Text = "Сохранить";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
// //
// openFileDialog // openFileDialog
// //
@ -194,13 +217,6 @@
// //
saveFileDialog.Filter = "«txt file | *.txt»"; saveFileDialog.Filter = "«txt file | *.txt»";
// //
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(180, 22);
SaveToolStripMenuItem.Text = "Сохранить";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// FormBusCollection // FormBusCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
@ -237,5 +253,7 @@
private ToolStripMenuItem ToolStripMenuItem; private ToolStripMenuItem ToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem; private ToolStripMenuItem LoadToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem; private ToolStripMenuItem SaveToolStripMenuItem;
private Button ButtonSortByColor;
private Button ButtonSortByType;
} }
} }

View File

@ -16,8 +16,6 @@ using DoubleDeckerBus.Exceptions;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System.Xml.Linq; using System.Xml.Linq;
namespace DoubleDeckerBus namespace DoubleDeckerBus
{ {
public partial class FormBusCollection : Form public partial class FormBusCollection : Form
@ -33,13 +31,13 @@ namespace DoubleDeckerBus
private void ReloadObjects() private void ReloadObjects()
{ {
int index = listBoxStorages.SelectedIndex; int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear(); listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++) for (int i = 0; i < _storage.Keys.Count; i++)
{ {
listBoxStorages.Items.Add(_storage.Keys[i]); listBoxStorages.Items.Add(_storage.Keys[i]);
} }
if (listBoxStorages.Items.Count > 0 && (index == -1 || index >= listBoxStorages.Items.Count)) if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count))
{ {
listBoxStorages.SelectedIndex = 0; listBoxStorages.SelectedIndex = 0;
} }
@ -60,7 +58,7 @@ namespace DoubleDeckerBus
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text.ToString());
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}"); _logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}");
} }
@ -85,30 +83,41 @@ namespace DoubleDeckerBus
{ {
return; return;
} }
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
string.Empty];
if (obj == null) if (obj == null)
{ {
return; return;
} }
FormBusConfig form = new(); FormBusConfig formBusConfig = new FormBusConfig();
form.Show(); formBusConfig.AddEvent(AddBus);
Action<DrawningBus>? busDelegate = new((m) => formBusConfig.Show();
}
private void AddBus(DrawningBus bus)
{
if (listBoxStorages.SelectedIndex == -1)
{ {
try return;
{ }
bool q = obj + m; var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
MessageBox.Show("Объект добавлен"); if (obj == null)
_logger.LogInformation($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}"); {
pictureBoxCollection.Image = obj.ShowBuses(); _logger.LogWarning("Добавление пустого объекта");
} return;
catch (StorageOverflowException ex) }
{ try
_logger.LogWarning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена"); {
MessageBox.Show(ex.Message); _ = obj + bus;
} MessageBox.Show("Объект добавлен");
}); pictureBoxCollection.Image = obj.ShowBuses();
form.AddEvent(busDelegate); _logger.LogInformation($"bus added in set {listBoxStorages.SelectedItem.ToString()}");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"bus not added in set {listBoxStorages.SelectedItem.ToString()}");
}
} }
private void buttonRemoveBus_Click(object sender, EventArgs e) private void buttonRemoveBus_Click(object sender, EventArgs e)
{ {
@ -116,7 +125,7 @@ namespace DoubleDeckerBus
{ {
return; return;
} }
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null) if (obj == null)
{ {
return; return;
@ -127,23 +136,23 @@ namespace DoubleDeckerBus
} }
try try
{ {
int pos = Convert.ToInt32(maskedTextBoxNumber.Text); int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null) if (obj - pos != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowBuses(); pictureBoxCollection.Image = obj.ShowBuses();
_logger.LogInformation($"лодка удалена из набора {listBoxStorages.SelectedItem.ToString()}"); _logger.LogInformation($"Автобус удален из набора {listBoxStorages.SelectedItem.ToString()}");
} }
else else
{ {
MessageBox.Show("Объект не удален"); MessageBox.Show("Объект не удален");
_logger.LogWarning($"лодка не удалена из набора {listBoxStorages.SelectedItem.ToString()}"); _logger.LogWarning($"Автобус не удален из набора {listBoxStorages.SelectedItem.ToString()}");
} }
} }
catch (BusNotFoundException ex) catch (BusNotFoundException ex)
{ {
MessageBox.Show(ex.Message); MessageBox.Show(ex.Message);
_logger.LogWarning($"BoatNotFound: {ex.Message} in set {listBoxStorages.SelectedItem.ToString()}"); _logger.LogWarning($"BusNotFound: {ex.Message} in set {listBoxStorages.SelectedItem.ToString()}");
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -170,13 +179,13 @@ namespace DoubleDeckerBus
try try
{ {
_storage.SaveData(saveFileDialog.FileName); _storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно","Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Файл {saveFileDialog.FileName} успешно сохранен"); _logger.LogInformation($"Файл {saveFileDialog.FileName} успешно сохранен");
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogWarning("Не удалось сохранить"); _logger.LogWarning("Не удалось сохранить");
MessageBox.Show($"Не сохранилось: {ex.Message}","Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
@ -189,7 +198,7 @@ namespace DoubleDeckerBus
try try
{ {
_storage.LoadData(openFileDialog.FileName); _storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно","Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Файл {openFileDialog.FileName} успешно загружен"); _logger.LogInformation($"Файл {openFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys) foreach (var collection in _storage.Keys)
{ {
@ -200,11 +209,27 @@ namespace DoubleDeckerBus
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogWarning("Не удалось загрузить"); _logger.LogWarning("Не удалось загрузить");
MessageBox.Show($"Не загрузилось: {ex.Message}","Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareBuses(new BusCompareByType());
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareBuses(new BusCompareByColor());
private void CompareBuses(IComparer<DrawningBus?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowBuses();
}
} }
} }

View File

@ -120,9 +120,6 @@
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>11, 17</value> <value>11, 17</value>
</metadata> </metadata>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>11, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>132, 17</value> <value>132, 17</value>
</metadata> </metadata>

View File

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DoubleDeckerBus.DrawningObjects;
using DoubleDeckerBus.Entities;
namespace DoubleDeckerBus.Generics
{
internal class BusCompareByColor : IComparer<DrawningBus?>
{
public int Compare(DrawningBus? x, DrawningBus? y)
{
if (x == null || x.EntityBus == null)
throw new ArgumentNullException(nameof(x));
if (y == null || y.EntityBus == null)
throw new ArgumentNullException(nameof(y));
var xCruiser = x.EntityBus;
var yCruiser = y.EntityBus;
if (xCruiser.BodyColor != yCruiser.BodyColor)
return xCruiser.BodyColor.Name.CompareTo(yCruiser.BodyColor.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

@ -0,0 +1,35 @@
using DoubleDeckerBus.DrawningObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DoubleDeckerBus.Generics
{
internal class BusCompareByType : IComparer<DrawningBus?>
{
public int Compare(DrawningBus? x, DrawningBus? y)
{
if (x == null || x.EntityBus == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityBus == null)
{
throw new ArgumentNullException(nameof(y));
}
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

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DoubleDeckerBus.Generics
{
internal class BusesCollectionInfo : IEquatable<BusesCollectionInfo>
{
public string Name { get; private set; }
public string Description { get; private set; }
public BusesCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(BusesCollectionInfo? other)
{
if (Name != other?.Name)
throw new NotImplementedException(nameof(Name));
return true;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
public override string ToString()
{
return Name;
}
}
}

View File

@ -12,6 +12,7 @@ namespace DoubleDeckerBus.Generics
where T : DrawningBus where T : DrawningBus
where U : IMoveableObject where U : IMoveableObject
{ {
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
public IEnumerable<T?> GetTheBuses => _collection.GetTheBuses(); public IEnumerable<T?> GetTheBuses => _collection.GetTheBuses();
private readonly int _pictureWidth; private readonly int _pictureWidth;
private readonly int _pictureHeight; private readonly int _pictureHeight;
@ -33,7 +34,7 @@ namespace DoubleDeckerBus.Generics
return false; return false;
} }
return collect?._collection.Insert(obj) ?? false; return collect._collection.Insert(obj, new DrawiningBusEqutables());
} }
public static T? operator -(BusesGenericCollection<T, U> collect, int pos) public static T? operator -(BusesGenericCollection<T, U> collect, int pos)
{ {

View File

@ -10,8 +10,8 @@ namespace DoubleDeckerBus.Generics
{ {
internal class BusesGenericStorage internal class BusesGenericStorage
{ {
readonly Dictionary<string, BusesGenericCollection<DrawningBus, DrawningObjectBus>> _busStorages; readonly Dictionary<BusesCollectionInfo, BusesGenericCollection<DrawningBus, DrawningObjectBus>> _busStorages;
public List<string> Keys => _busStorages.Keys.ToList(); public List<BusesCollectionInfo> Keys => _busStorages.Keys.ToList();
private readonly int _pictureWidth; private readonly int _pictureWidth;
private readonly int _pictureHeight; private readonly int _pictureHeight;
private static readonly char _separatorForKeyValue = '|'; private static readonly char _separatorForKeyValue = '|';
@ -19,32 +19,29 @@ namespace DoubleDeckerBus.Generics
private static readonly char _separatorForObject = ':'; private static readonly char _separatorForObject = ':';
public BusesGenericStorage(int pictureWidth, int pictureHeight) public BusesGenericStorage(int pictureWidth, int pictureHeight)
{ {
_busStorages = new Dictionary<string, BusesGenericCollection<DrawningBus, DrawningObjectBus>>(); _busStorages = new Dictionary<BusesCollectionInfo, BusesGenericCollection<DrawningBus, DrawningObjectBus>> ();
_pictureWidth = pictureWidth; _pictureWidth = pictureWidth;
_pictureHeight = pictureHeight; _pictureHeight = pictureHeight;
} }
public void AddSet(string name) public void AddSet(string name)
{ {
_busStorages.Add(name, new BusesGenericCollection<DrawningBus, DrawningObjectBus>(_pictureWidth, _pictureHeight)); _busStorages.Add(new BusesCollectionInfo(name, string.Empty),
new BusesGenericCollection<DrawningBus, DrawningObjectBus>(_pictureWidth, _pictureHeight));
} }
public void DelSet(string name) public void DelSet(string name)
{ {
if (!_busStorages.ContainsKey(name)) if (!_busStorages.ContainsKey(new BusesCollectionInfo(name, string.Empty)))
{
return; return;
} _busStorages.Remove(new BusesCollectionInfo(name, string.Empty));
_busStorages.Remove(name);
} }
public BusesGenericCollection<DrawningBus, DrawningObjectBus>?this[string ind]
public BusesGenericCollection<DrawningBus, DrawningObjectBus>? this[string ind]
{ {
get get
{ {
if (_busStorages.ContainsKey(ind)) BusesCollectionInfo indObj = new BusesCollectionInfo(ind, string.Empty);
{ if (_busStorages.ContainsKey(indObj))
return _busStorages[ind]; return _busStorages[indObj];
}
return null; return null;
} }
} }
@ -55,19 +52,18 @@ namespace DoubleDeckerBus.Generics
File.Delete(filename); File.Delete(filename);
} }
StringBuilder data = new(); StringBuilder data = new();
foreach (KeyValuePair<string, foreach (KeyValuePair<BusesCollectionInfo, BusesGenericCollection<DrawningBus, DrawningObjectBus>> record in _busStorages)
BusesGenericCollection<DrawningBus, DrawningObjectBus>> record in _busStorages)
{ {
StringBuilder records = new(); StringBuilder records = new();
foreach (DrawningBus? elem in record.Value.GetTheBuses) foreach (DrawningBus? elem in record.Value.GetTheBuses)
{ {
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
} }
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
} }
if (data.Length == 0) if (data.Length == 0)
{ {
throw new Exception("Невалидная операция, нет данных для сохранения"); throw new Exception("Невалиданя операция, нет данных для сохранения");
} }
using FileStream fs = new(filename, FileMode.Create); using FileStream fs = new(filename, FileMode.Create);
byte[] info = new byte[] info = new
@ -75,6 +71,7 @@ namespace DoubleDeckerBus.Generics
fs.Write(info, 0, info.Length); fs.Write(info, 0, info.Length);
return; return;
} }
public void LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
@ -91,8 +88,7 @@ namespace DoubleDeckerBus.Generics
bufferTextFromFile += temp.GetString(b); bufferTextFromFile += temp.GetString(b);
} }
} }
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0) if (strs == null || strs.Length == 0)
{ {
throw new Exception("Нет данных для загрузки"); throw new Exception("Нет данных для загрузки");
@ -105,8 +101,7 @@ namespace DoubleDeckerBus.Generics
_busStorages.Clear(); _busStorages.Clear();
foreach (string data in strs) foreach (string data in strs)
{ {
string[] record = data.Split(_separatorForKeyValue, string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2) if (record.Length != 2)
{ {
continue; continue;
@ -117,17 +112,16 @@ namespace DoubleDeckerBus.Generics
StringSplitOptions.RemoveEmptyEntries); StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
DrawningBus? car = DrawningBus? bus = elem?.CreateDrawningBus(_separatorForObject, _pictureWidth, _pictureHeight);
elem?.CreateDrawningBus(_separatorForObject, _pictureWidth, _pictureHeight); if (bus != null)
if (car != null)
{ {
if (!(collection + car)) if (!(collection + bus))
{ {
throw new Exception("Ошибка добавления в коллекцию"); throw new Exception("Ошибка добавления в коллекцию");
} }
} }
} }
_busStorages.Add(record[0], collection); _busStorages.Add(new BusesCollectionInfo(record[0], string.Empty), collection);
} }
} }
} }

View File

@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DoubleDeckerBus.DrawningObjects;
using DoubleDeckerBus.Entities;
namespace DoubleDeckerBus.Generics
{
internal class DrawiningBusEqutables : IEqualityComparer<DrawningBus?>
{
public bool Equals(DrawningBus? x, DrawningBus? y)
{
if (x == null || x.EntityBus == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityBus == null)
{
throw new ArgumentNullException(nameof(y));
}
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 DrawningDoubleDeckerBus && y is DrawningDoubleDeckerBus)
{
if ((x.EntityBus as EntityDoubleDeckerBus).AdditionalColor != (y.EntityBus as EntityDoubleDeckerBus).AdditionalColor)
{
return false;
}
if ((x.EntityBus as EntityDoubleDeckerBus).SecondFloor != (y.EntityBus as EntityDoubleDeckerBus).SecondFloor)
{
return false;
}
if ((x.EntityBus as EntityDoubleDeckerBus).Ladder != (y.EntityBus as EntityDoubleDeckerBus).Ladder)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningBus obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -14,24 +14,30 @@ namespace DoubleDeckerBus.Generics
private readonly List<T?> _places; private readonly List<T?> _places;
public int Count => _places.Count; public int Count => _places.Count;
private readonly int _maxCount; private readonly int _maxCount;
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
public SetGeneric(int count) public SetGeneric(int count)
{ {
_maxCount = count; _maxCount = count;
_places = new List<T?>(count); _places = new List<T?>(count);
} }
public bool Insert(T bus) public bool Insert(T bus, IEqualityComparer<T?>? equal = null)
{ {
if (_places.Count == _maxCount) if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount); throw new StorageOverflowException(_maxCount);
Insert(bus, 0); Insert(bus, 0, equal);
return true; return true;
} }
public bool Insert(T bus, int position) public bool Insert(T bus, int position, IEqualityComparer<T?>? equal = null)
{ {
if (_places.Count == _maxCount) if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount); throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count)) if (!(position >= 0 && position <= Count))
return false; return false;
if (equal != null)
{
if (_places.Contains(bus, equal))
throw new ArgumentException(("Такой объект уже существует"));
}
_places.Insert(position, bus); _places.Insert(position, bus);
return true; return true;
} }