Залил лаб4

This commit is contained in:
ujijrujijr 2023-10-25 21:44:34 +03:00
parent 3e84994000
commit 7b3777a796
5 changed files with 345 additions and 111 deletions

View File

@ -73,7 +73,7 @@ namespace Trolleybus.Generics
/// <returns></returns> /// <returns></returns>
public static bool operator -(BusesGenericCollection<T, U> collect, int pos) public static bool operator -(BusesGenericCollection<T, U> collect, int pos)
{ {
T? obj = collect._collection.Get(pos); T? obj = collect._collection[pos];
if (obj != null) if (obj != null)
{ {
collect._collection.Remove(pos); collect._collection.Remove(pos);
@ -90,7 +90,7 @@ namespace Trolleybus.Generics
/// <returns></returns> /// <returns></returns>
public U? GetU(int pos) public U? GetU(int pos)
{ {
return (U?)_collection.Get(pos)?.GetMoveableObject; return (U?)_collection[pos]?.GetMoveableObject;
} }
/// <summary> /// <summary>
/// Вывод всего набора объектов /// Вывод всего набора объектов
@ -134,9 +134,8 @@ namespace Trolleybus.Generics
{ {
int i = 0; int i = 0;
int j = _pictureWidth / _placeSizeWidth - 1; int j = _pictureWidth / _placeSizeWidth - 1;
for (int k = 0; k < _collection.Count; k++) foreach (var bus in _collection.GetBuses())
{ {
DrawingBus bus = _collection.Get(k);
if (bus != null) if (bus != null)
{ {
bus.SetPosition(j * (_placeSizeWidth + 10) + 5, i * (_placeSizeHeight) + 10); bus.SetPosition(j * (_placeSizeWidth + 10) + 5, i * (_placeSizeHeight) + 10);
@ -149,7 +148,6 @@ namespace Trolleybus.Generics
j = _pictureWidth / _placeSizeWidth - 1; j = _pictureWidth / _placeSizeWidth - 1;
i++; i++;
} }
} }
} }
} }

View File

@ -0,0 +1,89 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Trolleybus.DrawingObjects;
using Trolleybus.MovementStrategy;
namespace Trolleybus.Generics
{
internal class BusesGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, BusesGenericCollection<DrawingBus, DrawingObjectBus>> _busStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _busStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public BusesGenericStorage(int pictureWidth, int pictureHeight)
{
_busStorages = new Dictionary<string, BusesGenericCollection<DrawingBus, DrawingObjectBus>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
// проверка, существует ли набор с таким ключём
if (_busStorages.ContainsKey(name))
{
return;
}
var busCollection = new BusesGenericCollection<DrawingBus, DrawingObjectBus>(_pictureWidth, _pictureHeight);
_busStorages.Add(name, busCollection);
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (_busStorages.ContainsKey(name))
{
_busStorages.Remove(name);
}
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public BusesGenericCollection<DrawingBus, DrawingObjectBus>? this[string ind]
{
get
{
if (!_busStorages.ContainsKey(ind))
{
return null;
}
return _busStorages[ind];
}
}
}
}

View File

@ -18,14 +18,78 @@ namespace Trolleybus
/// <summary> /// <summary>
/// Набор объектов /// Набор объектов
/// </summary> /// </summary>
private readonly BusesGenericCollection<DrawingBus, DrawingObjectBus> _buses; private readonly BusesGenericStorage _storage;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormBusesCollection() public FormBusesCollection()
{ {
InitializeComponent(); InitializeComponent();
_buses = new BusesGenericCollection<DrawingBus, DrawingObjectBus>(pictureBoxCollection.Width, pictureBoxCollection.Height); _storage = new BusesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
/// <summary>
/// Заполнение listBoxObjects
/// </summary>
private void ReloadObjects()
{
int index = listBoxSets.SelectedIndex;
listBoxSets.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxSets.Items.Add(_storage.Keys[i]);
}
if (listBoxSets.Items.Count > 0 && (index == -1 || index >= listBoxSets.Items.Count))
{
listBoxSets.SelectedIndex = 0;
}
else if (listBoxSets.Items.Count > 0 && index > -1 && index < listBoxSets.Items.Count)
{
listBoxSets.SelectedIndex = index;
}
}
/// <summary>
/// Добавление набора в коллекцию
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddSetOfObjects_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxNameOfSet.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxNameOfSet.Text);
ReloadObjects();
}
/// <summary>
/// Выбор набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListBoxSets_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCollection.Image = _storage[listBoxSets.SelectedItem?.ToString() ?? string.Empty]?.ShowBuses();
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDeleteSetOfObjects_Click(object sender, EventArgs e)
{
if (listBoxSets.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить объект {listBoxSets.SelectedItem}?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxSets.SelectedItem.ToString() ?? string.Empty);
ReloadObjects();
}
} }
/// <summary> /// <summary>
/// Добавление объекта в набор /// Добавление объекта в набор
@ -34,13 +98,23 @@ namespace Trolleybus
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonAddBus_Click(object sender, EventArgs e) private void ButtonAddBus_Click(object sender, EventArgs e)
{ {
if (listBoxSets.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxSets.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
FormTrolleybus form = new FormTrolleybus(); FormTrolleybus form = new FormTrolleybus();
if (form.ShowDialog() == DialogResult.OK) if (form.ShowDialog() == DialogResult.OK)
{ {
if (_buses + form.SelectedBus != -1) if (obj + form.SelectedBus != -1)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _buses.ShowBuses(); pictureBoxCollection.Image = obj.ShowBuses();
} }
else else
{ {
@ -55,6 +129,15 @@ namespace Trolleybus
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonRemoveBus_Click(object sender, EventArgs e) private void ButtonRemoveBus_Click(object sender, EventArgs e)
{ {
if (listBoxSets.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxSets.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
@ -66,10 +149,10 @@ namespace Trolleybus
pos_string = "0"; pos_string = "0";
} }
int pos = Convert.ToInt32(pos_string); int pos = Convert.ToInt32(pos_string);
if (_buses - pos) if (obj - pos)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBoxCollection.Image = _buses.ShowBuses(); pictureBoxCollection.Image = obj.ShowBuses();
} }
else else
{ {
@ -83,19 +166,34 @@ namespace Trolleybus
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonRefreshCollection_Click(object sender, EventArgs e) private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{ {
pictureBoxCollection.Image = _buses.ShowBuses(); if (listBoxSets.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxSets.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowBuses();
} }
private void InitializeComponent() private void InitializeComponent()
{ {
pictureBoxCollection = new PictureBox(); pictureBoxCollection = new PictureBox();
panelTools = new Panel(); panelTools = new Panel();
panelSets = new Panel();
buttonDeleteSetOfObjects = new Button();
textBoxNameOfSet = new TextBox();
listBoxSets = new ListBox();
buttonAddSetOfObjects = new Button();
buttonRefreshCollection = new Button(); buttonRefreshCollection = new Button();
maskedTextBoxNumber = new MaskedTextBox(); maskedTextBoxNumber = new MaskedTextBox();
buttonRemoveBus = new Button(); buttonRemoveBus = new Button();
buttonAddBus = new Button(); buttonAddBus = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
panelTools.SuspendLayout(); panelTools.SuspendLayout();
panelSets.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// pictureBoxCollection // pictureBoxCollection
@ -103,25 +201,77 @@ namespace Trolleybus
pictureBoxCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; pictureBoxCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
pictureBoxCollection.Location = new Point(0, 0); pictureBoxCollection.Location = new Point(0, 0);
pictureBoxCollection.Name = "pictureBoxCollection"; pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(670, 453); pictureBoxCollection.Size = new Size(670, 553);
pictureBoxCollection.TabIndex = 0; pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false; pictureBoxCollection.TabStop = false;
// //
// panelTools // panelTools
// //
panelTools.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right; panelTools.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right;
panelTools.BorderStyle = BorderStyle.FixedSingle;
panelTools.Controls.Add(panelSets);
panelTools.Controls.Add(buttonRefreshCollection); panelTools.Controls.Add(buttonRefreshCollection);
panelTools.Controls.Add(maskedTextBoxNumber); panelTools.Controls.Add(maskedTextBoxNumber);
panelTools.Controls.Add(buttonRemoveBus); panelTools.Controls.Add(buttonRemoveBus);
panelTools.Controls.Add(buttonAddBus); panelTools.Controls.Add(buttonAddBus);
panelTools.Location = new Point(682, 0); panelTools.Location = new Point(682, 0);
panelTools.Name = "panelTools"; panelTools.Name = "panelTools";
panelTools.Size = new Size(200, 453); panelTools.Size = new Size(200, 553);
panelTools.TabIndex = 1; panelTools.TabIndex = 1;
// //
// panelSets
//
panelSets.Anchor = AnchorStyles.Top | AnchorStyles.Right;
panelSets.BorderStyle = BorderStyle.FixedSingle;
panelSets.Controls.Add(buttonDeleteSetOfObjects);
panelSets.Controls.Add(textBoxNameOfSet);
panelSets.Controls.Add(listBoxSets);
panelSets.Controls.Add(buttonAddSetOfObjects);
panelSets.Location = new Point(17, 11);
panelSets.Name = "panelSets";
panelSets.Size = new Size(170, 283);
panelSets.TabIndex = 4;
//
// buttonDeleteSetOfObjects
//
buttonDeleteSetOfObjects.Location = new Point(3, 222);
buttonDeleteSetOfObjects.Name = "buttonDeleteSetOfObjects";
buttonDeleteSetOfObjects.Size = new Size(162, 45);
buttonDeleteSetOfObjects.TabIndex = 3;
buttonDeleteSetOfObjects.Text = "Удалить набор";
buttonDeleteSetOfObjects.UseVisualStyleBackColor = true;
buttonDeleteSetOfObjects.Click += ButtonDeleteSetOfObjects_Click;
//
// textBoxNameOfSet
//
textBoxNameOfSet.Location = new Point(3, 19);
textBoxNameOfSet.Name = "textBoxNameOfSet";
textBoxNameOfSet.Size = new Size(162, 27);
textBoxNameOfSet.TabIndex = 2;
//
// listBoxSets
//
listBoxSets.FormattingEnabled = true;
listBoxSets.ItemHeight = 20;
listBoxSets.Location = new Point(3, 112);
listBoxSets.Name = "listBoxSets";
listBoxSets.Size = new Size(162, 104);
listBoxSets.TabIndex = 1;
listBoxSets.SelectedIndexChanged += ListBoxSets_SelectedIndexChanged;
//
// buttonAddSetOfObjects
//
buttonAddSetOfObjects.Location = new Point(3, 52);
buttonAddSetOfObjects.Name = "buttonAddSetOfObjects";
buttonAddSetOfObjects.Size = new Size(162, 45);
buttonAddSetOfObjects.TabIndex = 0;
buttonAddSetOfObjects.Text = "Добавить набор";
buttonAddSetOfObjects.UseVisualStyleBackColor = true;
buttonAddSetOfObjects.Click += ButtonAddSetOfObjects_Click;
//
// buttonRefreshCollection // buttonRefreshCollection
// //
buttonRefreshCollection.Location = new Point(17, 190); buttonRefreshCollection.Location = new Point(17, 484);
buttonRefreshCollection.Name = "buttonRefreshCollection"; buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(170, 40); buttonRefreshCollection.Size = new Size(170, 40);
buttonRefreshCollection.TabIndex = 3; buttonRefreshCollection.TabIndex = 3;
@ -131,7 +281,7 @@ namespace Trolleybus
// //
// maskedTextBoxNumber // maskedTextBoxNumber
// //
maskedTextBoxNumber.Location = new Point(39, 76); maskedTextBoxNumber.Location = new Point(39, 366);
maskedTextBoxNumber.Mask = "00"; maskedTextBoxNumber.Mask = "00";
maskedTextBoxNumber.Name = "maskedTextBoxNumber"; maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(125, 27); maskedTextBoxNumber.Size = new Size(125, 27);
@ -140,7 +290,7 @@ namespace Trolleybus
// //
// buttonRemoveBus // buttonRemoveBus
// //
buttonRemoveBus.Location = new Point(17, 125); buttonRemoveBus.Location = new Point(17, 409);
buttonRemoveBus.Name = "buttonRemoveBus"; buttonRemoveBus.Name = "buttonRemoveBus";
buttonRemoveBus.Size = new Size(170, 40); buttonRemoveBus.Size = new Size(170, 40);
buttonRemoveBus.TabIndex = 1; buttonRemoveBus.TabIndex = 1;
@ -150,7 +300,7 @@ namespace Trolleybus
// //
// buttonAddBus // buttonAddBus
// //
buttonAddBus.Location = new Point(17, 12); buttonAddBus.Location = new Point(17, 311);
buttonAddBus.Name = "buttonAddBus"; buttonAddBus.Name = "buttonAddBus";
buttonAddBus.Size = new Size(170, 40); buttonAddBus.Size = new Size(170, 40);
buttonAddBus.TabIndex = 0; buttonAddBus.TabIndex = 0;
@ -158,16 +308,18 @@ namespace Trolleybus
buttonAddBus.UseVisualStyleBackColor = true; buttonAddBus.UseVisualStyleBackColor = true;
buttonAddBus.Click += ButtonAddBus_Click; buttonAddBus.Click += ButtonAddBus_Click;
// //
// FormBusCollection // FormBusesCollection
// //
ClientSize = new Size(882, 453); ClientSize = new Size(882, 553);
Controls.Add(panelTools); Controls.Add(panelTools);
Controls.Add(pictureBoxCollection); Controls.Add(pictureBoxCollection);
Name = "FormBusCollection"; Name = "FormBusesCollection";
Text = "Набор автобусов"; Text = "Набор автобусов";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
panelTools.ResumeLayout(false); panelTools.ResumeLayout(false);
panelTools.PerformLayout(); panelTools.PerformLayout();
panelSets.ResumeLayout(false);
panelSets.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
} }
@ -176,6 +328,12 @@ namespace Trolleybus
private Button buttonRefreshCollection; private Button buttonRefreshCollection;
private MaskedTextBox maskedTextBoxNumber; private MaskedTextBox maskedTextBoxNumber;
private Button buttonRemoveBus; private Button buttonRemoveBus;
private Panel panelSets;
private Button buttonAddSetOfObjects;
private ListBox listBoxSets;
private TextBox textBoxNameOfSet;
private Button buttonDeleteSetOfObjects;
private Button buttonAddBus; private Button buttonAddBus;
} }
} }

View File

@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<root> <root>
<!-- <!--
Microsoft ResX Schema Microsoft ResX Schema
Version 2.0 Version 2.0
The primary goals of this format is to allow a simple XML format The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes various data types are done through the TypeConverter classes
associated with the data types. associated with the data types.
Example: Example:
... ado.net/XML headers & schema ... ... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader> <resheader name="version">2.0</resheader>
@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment> <comment>This is a comment</comment>
</data> </data>
There are any number of "resheader" rows that contain simple There are any number of "resheader" rows that contain simple
name/value pairs. name/value pairs.
Each data row contains a name, and value. The row also contains a Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture. text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the Classes that don't support this are serialized and stored with the
mimetype set. mimetype set.
The mimetype is used for serialized objects, and tells the The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly: extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below. read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64 mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64 mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64 mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter : using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
--> -->

View File

@ -14,20 +14,25 @@ namespace Trolleybus.Generics
where T : class where T : class
{ {
/// <summary> /// <summary>
/// Массив объектов, которые храним /// Список объектов, которые храним
/// </summary> /// </summary>
private readonly T?[] _places; private readonly List<T>? _places;
/// <summary> /// <summary>
/// Количество объектов в массиве /// Количество объектов в списке
/// </summary> /// </summary>
public int Count => _places.Length; public int Count => _places.Count;
/// <summary>
/// Максимальное количество объектов в списке
/// </summary>
private readonly int _maxCount;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
/// <param name="count"></param> /// <param name="count"></param>
public SetGeneric(int count) public SetGeneric(int count)
{ {
_places = new T?[count]; _maxCount = count;
_places = new List<T?>(count);
} }
/// <summary> /// <summary>
/// Добавление объекта в начало набора /// Добавление объекта в начало набора
@ -36,35 +41,14 @@ namespace Trolleybus.Generics
/// <returns></returns> /// <returns></returns>
public int Insert(T bus) public int Insert(T bus)
{ {
if (_places[0] == null) if (Count + 1 <= _maxCount)
{ {
_places[0] = bus; _places.Insert(0, bus);
//0 в данном случае - индекс в массиве, вставка прошла успешно //0 в данном случае место, на котоорое добавился элемннт, вставка прошла успешно
return 0; return 0;
} }
else //если при добавлении в списке станет больше макс. кол-ва элементов, то как бы вставлять будет некуда
{ return -1;
int index = 0;
while (_places[index] != null)
{
index++;
if (index >= Count)
{
//места в массиве нет, ни по какому индексу вставить нельзя
return -1;
}
}
//cдвиг элементов
for (int i = index; i > 0; i--)
{
_places[i] = _places[i - 1];
}
_places[0] = bus;
//0 в данном случае - индекс в массиве, вставка прошла успешно
return 0;
}
} }
/// <summary> /// <summary>
/// Добавление объекта в набор на конкретную позицию /// Добавление объекта в набор на конкретную позицию
@ -74,40 +58,19 @@ namespace Trolleybus.Generics
/// <returns></returns> /// <returns></returns>
public int Insert(T bus, int position) public int Insert(T bus, int position)
{ {
if (position >= Count || position < 0) if (position >= _maxCount || position < 0)
{ {
//индекс неверный, значит вставить по индексу нельзя //позиция неверная, значит вставить нельзя
return -1; return -1;
} }
if (_places[position] == null) if (Count + 1 <= _maxCount)
{ {
_places[position] = bus; _places.Insert(position, bus);
//место в списке, по которому вставили, вставка прошла успешно
return position;
} }
else //места в списке нет
{ return -1;
//проверка, что в массиве после вставляемого эл-а есть место
int index = position;
while (_places[index] != null)
{
index++;
if (index >= Count)
{
//места в массиве нет, ни по какому индексу вставить нельзя
return -1;
}
}
//сдвиг элементов
for (int i = index; i > position; i--)
{
_places[i] = _places[i - 1];
}
//вставка по позиции
_places[position] = bus;
}
//индекс в массиве, по которому вставили, вставка прошла успешно
return position;
} }
/// <summary> /// <summary>
/// Удаление объекта из набора с конкретной позиции /// Удаление объекта из набора с конкретной позиции
@ -120,7 +83,7 @@ namespace Trolleybus.Generics
{ {
return false; return false;
} }
_places[position] = null; _places.RemoveAt(position);
return true; return true;
} }
/// <summary> /// <summary>
@ -128,13 +91,39 @@ namespace Trolleybus.Generics
/// </summary> /// </summary>
/// <param name="position"></param> /// <param name="position"></param>
/// <returns></returns> /// <returns></returns>
public T? Get(int position) public T? this[int position]
{ {
if (position >= Count || position < 0) get
{ {
return null; if (position >= Count || position < 0)
{
return null;
}
return _places[position];
}
set
{
if (position >= Count || position < 0)
{
return;
}
_places[position] = value;
}
}
/// <summary>
/// Проход по списку
/// </summary>
/// <returns></returns>
public IEnumerable<T?> GetBuses(int? maxBuses = null)
{
for (int i = 0; i < Count; ++i)
{
yield return _places[i];
if (maxBuses.HasValue && i == maxBuses.Value)
{
yield break;
}
} }
return _places[position];
} }
} }
} }