Лаба 6 правки

This commit is contained in:
Aleksandr4350 2024-05-22 23:03:52 +04:00
parent cf26999d5d
commit ef133ccb2c
13 changed files with 444 additions and 33 deletions

View File

@ -41,7 +41,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
_collection.MaxCount = GetMaxCount;
}
/// <summary>
/// Перегрузка оператора сложения для класса

View File

@ -13,7 +13,12 @@ where T : class
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию
/// </summary>
@ -39,4 +44,14 @@ where T : class
/// <param name="position">Позиция</param>
/// <returns>Объект</returns>
T? Get(int position);
/// <summary>
/// получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// получение объектов коллекции по одному
/// </summary>
/// <returns></returns>
IEnumerable<T?> GetItems();
}

View File

@ -11,7 +11,24 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
/// </summary>
private int _maxCount;
public int Count => _collection.Count;//свойство
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
public int MaxCount
{
get
{
return Count;
}
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
/// </summary>
@ -52,4 +69,12 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
_collection.RemoveAt(position);//метод
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; i++)
{
yield return _collection[i];
}
}
}

View File

@ -12,8 +12,14 @@ where T : class
/// </summary>
private T?[] _collection;
public int Count => _collection.Length;
public int SetMaxCount
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
@ -29,6 +35,9 @@ where T : class
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
@ -107,4 +116,12 @@ where T : class
return obj;
}
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; i++)
{
yield return _collection[i];
}
}
}

View File

@ -1,10 +1,13 @@
namespace ProjectAiroplane.CollectionGenericObjects;
using ProjectAiroplane.Drawnings;
using System.Text;
namespace ProjectAiroplane.CollectionGenericObjects;
/// <summary>
/// класс-хранилище
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : Drawningplane
{
/// <summary>
/// Словарь (хранилище) с коллекциями
@ -64,4 +67,148 @@ public class StorageCollection<T>
return null;
}
}
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при
///сохранении данных</returns>
public bool SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;///////////////////////
if (string.IsNullOrEmpty(data))
{
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
}
writer.Write(sb);
}
}
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке
///данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
return false;
}
if (!str.StartsWith(_collectionKey))
{
return false;
}
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
//
if (strs == null)
{
return false;
}
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);//////////////////CreateCollection
if (collection == null)
{
return false;
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningplane() is T airoplane)//////////////////////////////////////////////////////////////////CreateDrawningplane()
{
if (collection.Insert(airoplane) == -1)
{
return false;
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

@ -15,15 +15,20 @@ public class DrawningAiroplane : Drawningplane
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="toplivbak">Признак наличия бака</param>
/// <param name="radar">Признак наличия радара</param>
public DrawningAiroplane(int speed, double weight, Color bodyColor, Color additionalColor, bool toplivbak, bool radar) : base(170,85)
public DrawningAiroplane(int speed, double weight, Color bodyColor, Color additionalColor, bool toplivbak, bool radar) : base(170, 85)
{
Entityplane = new EntityAiroplane(speed, weight, bodyColor, additionalColor, toplivbak, radar);
}
public DrawningAiroplane(EntityAiroplane airoplane) : base(170, 85)
{
Entityplane = new EntityAiroplane(airoplane.Speed, airoplane.Weight, airoplane.BodyColor, airoplane.AdditionalColor, airoplane.Toplivbak, airoplane.Radar);
}
public override void DrawTransport(Graphics g)
{
if (Entityplane == null || Entityplane is not EntityAiroplane airoplane|| !_startPosX.HasValue || !_startPosY.HasValue)
if (Entityplane == null || Entityplane is not EntityAiroplane airoplane || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
@ -33,9 +38,9 @@ public class DrawningAiroplane : Drawningplane
Brush additionalBrush = new SolidBrush(airoplane.AdditionalColor);
if (airoplane.Toplivbak)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 65,_startPosY.Value + 20, 30, 15);
g.FillRectangle(additionalBrush, _startPosX.Value + 65, _startPosY.Value + 20, 30, 15);
}
//Радар
if (airoplane.Radar)
{

View File

@ -73,6 +73,12 @@ public class Drawningplane
Entityplane = new Entityplane(speed, weight, bodyColor);
}
public Drawningplane(Entityplane airoplane) : this()
{
Entityplane = new Entityplane(airoplane.Speed, airoplane.Weight, airoplane.BodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>

View File

@ -0,0 +1,50 @@
using ProjectAiroplane.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAiroplane.Drawnings;
public static class ExtentionDrawningPlane
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static Drawningplane? CreateDrawningplane(this string info)
{
string[] strs = info.Split(_separatorForObject);
Entityplane? airoplane = EntityAiroplane.CreateEntityAiroplane(strs);
if (airoplane != null)
{
return new DrawningAiroplane((EntityAiroplane)airoplane);
}
airoplane = Entityplane.CreateEntityplane(strs);
if (airoplane != null)
{
return new Drawningplane(airoplane);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningplane">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this Drawningplane drawningplane)
{
string[]? array = drawningplane?.Entityplane?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -1,4 +1,6 @@
namespace ProjectAiroplane.Entities;
using System.Net.Sockets;
namespace ProjectAiroplane.Entities;
public class EntityAiroplane : Entityplane
{
/// <summary>
@ -13,7 +15,7 @@ public class EntityAiroplane : Entityplane
/// Признак (опция) наличия радара
/// </summary>
public bool Radar { get; private set; }
/// <summary>
/// Инициализация полей класса
/// </summary>
@ -23,7 +25,7 @@ public class EntityAiroplane : Entityplane
/// <param name="additionalColor"></Дополнительный цвет>
/// <param name="toplivbak"></ Признак наличия бака>
/// <param name="radar"></Признак (опция) наличия радара>
public EntityAiroplane(int speed, double weight, Color bodyColor, Color additionalColor, bool toplivbak, bool radar) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
@ -39,6 +41,28 @@ public class EntityAiroplane : Entityplane
{
AdditionalColor = color;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityAiroplane), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Toplivbak.ToString(), Radar.ToString() };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityAiroplane? CreateEntityAiroplane(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityAiroplane))
{
return null;
}
return new EntityAiroplane(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
}

View File

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
@ -52,5 +53,27 @@ public class Entityplane
BodyColor = bodyColor;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(Entityplane), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static Entityplane? CreateEntityplane(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(Entityplane))
{
return null;
}
return new Entityplane(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}

View File

@ -30,6 +30,7 @@
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonAddPlane = new Button();
buttonGoToCheck = new Button();
buttonDelPlane = new Button();
maskedTextBox1 = new MaskedTextBox();
@ -45,11 +46,17 @@
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
buttonAddPlane = new Button();
menuStrip1 = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip1.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
@ -59,9 +66,9 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(859, 0);
groupBoxTools.Location = new Point(859, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(277, 680);
groupBoxTools.Size = new Size(277, 652);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -79,9 +86,19 @@
panelCompanyTools.Size = new Size(268, 322);
panelCompanyTools.TabIndex = 9;
//
// buttonAddPlane
//
buttonAddPlane.Location = new Point(7, 14);
buttonAddPlane.Name = "buttonAddPlane";
buttonAddPlane.Size = new Size(252, 40);
buttonAddPlane.TabIndex = 1;
buttonAddPlane.Text = "Добавление самолёта";
buttonAddPlane.UseVisualStyleBackColor = true;
buttonAddPlane.Click += ButtonAddPlane_Click;
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(7, 189);
buttonGoToCheck.Location = new Point(4, 168);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(254, 42);
buttonGoToCheck.TabIndex = 5;
@ -91,7 +108,7 @@
//
// buttonDelPlane
//
buttonDelPlane.Location = new Point(7, 140);
buttonDelPlane.Location = new Point(4, 119);
buttonDelPlane.Name = "buttonDelPlane";
buttonDelPlane.Size = new Size(254, 43);
buttonDelPlane.TabIndex = 4;
@ -101,7 +118,7 @@
//
// maskedTextBox1
//
maskedTextBox1.Location = new Point(7, 107);
maskedTextBox1.Location = new Point(7, 74);
maskedTextBox1.Mask = "00";
maskedTextBox1.Name = "maskedTextBox1";
maskedTextBox1.Size = new Size(252, 27);
@ -110,7 +127,7 @@
//
// buttonReFresh
//
buttonReFresh.Location = new Point(7, 237);
buttonReFresh.Location = new Point(4, 220);
buttonReFresh.Name = "buttonReFresh";
buttonReFresh.Size = new Size(252, 40);
buttonReFresh.TabIndex = 6;
@ -225,21 +242,50 @@
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(859, 680);
pictureBox.Size = new Size(859, 652);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// buttonAddPlane
// menuStrip1
//
buttonAddPlane.Location = new Point(7, 14);
buttonAddPlane.Name = "buttonAddPlane";
buttonAddPlane.Size = new Size(252, 40);
buttonAddPlane.TabIndex = 1;
buttonAddPlane.Text = "Добавление самолёта";
buttonAddPlane.UseVisualStyleBackColor = true;
buttonAddPlane.Click += ButtonAddPlane_Click;
menuStrip1.ImageScalingSize = new Size(20, 20);
menuStrip1.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(1136, 28);
menuStrip1.TabIndex = 2;
menuStrip1.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(227, 26);
saveToolStripMenuItem.Text = "Сохранение";
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(227, 26);
loadToolStripMenuItem.Text = "Загрузка";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormPlaneCollection
//
@ -248,6 +294,8 @@
ClientSize = new Size(1136, 680);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Name = "FormPlaneCollection";
Text = "Коллекция самолётов";
groupBoxTools.ResumeLayout(false);
@ -256,7 +304,10 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@ -279,5 +330,11 @@
private Button buttonCreateCompany;
private Panel panelCompanyTools;
private Button buttonAddPlane;
private MenuStrip menuStrip1;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -39,13 +39,13 @@ public partial class FormPlaneCollection : Form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddPlane_Click(object sender, EventArgs e)//вопрос 2 ...........................................................
private void ButtonAddPlane_Click(object sender, EventArgs e)
{
FormPlanConfig form = new();
// TODO передать метод
form.Show();
form.AddEvent(SetPlane); //////////////////////////////
form.AddEvent(SetPlane);
}
@ -238,4 +238,37 @@ public partial class FormPlaneCollection : Form
RerfreshListBoxItems();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
{
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
}
else
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -117,4 +117,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>153, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>323, 17</value>
</metadata>
</root>