hu
This commit is contained in:
parent
24afbe9254
commit
1ada437aae
@ -9,33 +9,27 @@ public abstract class AbstractCompany
|
||||
/// <summary>
|
||||
/// Размер места (ширина)
|
||||
/// </summary>
|
||||
protected readonly int _placeSizeWidth = 295;
|
||||
|
||||
protected readonly int _placeSizeWidth = 240;
|
||||
/// <summary>
|
||||
/// Размер места (высота)
|
||||
/// </summary>
|
||||
protected readonly int _placeSizeHeight = 160;
|
||||
|
||||
protected readonly int _placeSizeHeight = 50;
|
||||
/// <summary>
|
||||
/// Ширина окна
|
||||
/// </summary>
|
||||
protected readonly int _pictureWidth;
|
||||
|
||||
/// <summary>
|
||||
/// Высота окна
|
||||
/// </summary>
|
||||
protected readonly int _pictureHeight;
|
||||
|
||||
/// <summary>
|
||||
/// Коллекция автомобилей
|
||||
/// </summary>
|
||||
protected ICollectionGenericObjects<DrawningMachine>? _collection = null;
|
||||
|
||||
/// <summary>
|
||||
/// Вычисление максимального количества элементов, который можно разместить в окне
|
||||
/// </summary>
|
||||
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
@ -49,29 +43,31 @@ public abstract class AbstractCompany
|
||||
_collection = collection;
|
||||
_collection.MaxCount = GetMaxCount;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Перегрузка оператора сложения для класса
|
||||
/// </summary>
|
||||
/// <param name="company">Компания</param>
|
||||
/// <param name="car">Добавляемый объект</param>
|
||||
/// <returns></returns>
|
||||
public static int operator +(AbstractCompany company, DrawningMachine machine)
|
||||
public static bool operator +(AbstractCompany company, DrawningMachine bus)
|
||||
{
|
||||
return company._collection.Insert(machine);
|
||||
return company._collection?.Insert(bus, new DrawiningMachineEqutables()) != -1 ? true : false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Перегрузка оператора удаления для класса
|
||||
/// </summary>
|
||||
/// <param name="company">Компания</param>
|
||||
/// <param name="position">Номер удаляемого объекта</param>
|
||||
/// <returns></returns>
|
||||
public static DrawningMachine? operator -(AbstractCompany company, int position)
|
||||
public static DrawningMachine operator -(AbstractCompany? company, int position)
|
||||
{
|
||||
return company._collection?.Remove(position) ?? null;
|
||||
return company._collection.Remove(position);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сортировка
|
||||
/// </summary>
|
||||
/// <param name="comparer">Сравнитель объектов</param>
|
||||
public void Sort(IComparer<DrawningMachine?> comparer) => _collection?.CollectionSort(comparer);
|
||||
/// <summary>
|
||||
/// Получение случайного объекта из коллекции
|
||||
/// </summary>
|
||||
@ -81,7 +77,6 @@ public abstract class AbstractCompany
|
||||
Random rnd = new();
|
||||
return _collection?.Get(rnd.Next(GetMaxCount));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Вывод всей коллекции
|
||||
/// </summary>
|
||||
@ -91,23 +86,23 @@ public abstract class AbstractCompany
|
||||
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
|
||||
Graphics graphics = Graphics.FromImage(bitmap);
|
||||
DrawBackgound(graphics);
|
||||
|
||||
SetObjectsPosition();
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
|
||||
{
|
||||
DrawningMachine? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
try
|
||||
{
|
||||
DrawningMachine? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Вывод заднего фона
|
||||
/// </summary>
|
||||
/// <param name="g"></param>
|
||||
protected abstract void DrawBackgound(Graphics g);
|
||||
|
||||
/// <summary>
|
||||
/// Расстановка объектов
|
||||
/// </summary>
|
||||
|
73
Tank/Tank/CollectionGenericObjects/CollectionInfo.cs
Normal file
73
Tank/Tank/CollectionGenericObjects/CollectionInfo.cs
Normal file
@ -0,0 +1,73 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Tank.CollectionGenericObjects;
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
@ -53,4 +53,24 @@ where T : class
|
||||
/// </summary>
|
||||
/// <returns>Поэлементый вывод элементов коллекции</returns>
|
||||
IEnumerable<T?> GetItems();
|
||||
/// <summary>
|
||||
/// Добавление объекта в коллекцию
|
||||
/// </summary>
|
||||
/// <param name="obj">Добавляемый объект</param>
|
||||
/// <param name="comparer">Cравнение двух объектов</param>
|
||||
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
|
||||
int Insert(T obj, IEqualityComparer<DrawningMachine?>? comparer = null);
|
||||
/// Добавление объекта в коллекцию на конкретную позицию
|
||||
/// </summary>
|
||||
/// <param name="obj">Добавляемый объект</param>
|
||||
/// <param name="position">Позиция</param>
|
||||
/// <param name="comparer">Cравнение двух объектов</param>
|
||||
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
|
||||
int Insert(T obj, int position, IEqualityComparer<DrawningMachine?>? comparer = null);
|
||||
/// <summary>
|
||||
/// Сортировка коллекции
|
||||
/// </summary>
|
||||
/// <param name="comparer">Сравнитель объектов</param>
|
||||
void CollectionSort(IComparer<T?> comparer);
|
||||
|
||||
}
|
@ -3,6 +3,7 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Tank.Drowings;
|
||||
using Tank.Exceptions;
|
||||
|
||||
namespace Tank.CollectionGenericObjects;
|
||||
@ -108,4 +109,27 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
|
||||
public int Insert(T obj, IEqualityComparer<DrawningMachine?>? comparer = null)
|
||||
{
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
_collection.Add(obj);
|
||||
return Count;
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position, IEqualityComparer<DrawningMachine?>? comparer = null)
|
||||
{
|
||||
if (position < 0 || position >= Count)
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
|
||||
if (Count == _maxCount)
|
||||
throw new CollectionOverflowException(Count);
|
||||
_collection.Insert(position, obj);
|
||||
return position;
|
||||
}
|
||||
|
||||
public void CollectionSort(IComparer<T?> comparer)
|
||||
{
|
||||
_collection.Sort(comparer);
|
||||
}
|
||||
}
|
@ -1,4 +1,5 @@
|
||||
using Tank.CollectionGenericObjects;
|
||||
using Tank.Drowings;
|
||||
using Tank.Exceptions;
|
||||
|
||||
namespace Tank.CollectionGenericObjects;
|
||||
@ -125,4 +126,55 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
public int Insert(T obj, IEqualityComparer<DrawningMachine?>? comparer = null)
|
||||
{
|
||||
for (int i = 0; i < _collection.Length; i++)
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
{
|
||||
_collection[i] = obj;
|
||||
return i;
|
||||
}
|
||||
}
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position, IEqualityComparer<DrawningMachine?>? comparer = null)
|
||||
{
|
||||
if (position < 0 || position >= _collection.Length)
|
||||
{
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int i = position; i < _collection.Length; ++i) //ищем свободное место справа
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
{
|
||||
_collection[i] = obj;
|
||||
return i;
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < position; ++i) // иначе слева
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
{
|
||||
_collection[i] = obj;
|
||||
return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public void CollectionSort(IComparer<T?> comparer)
|
||||
{
|
||||
Array.Sort(_collection, comparer);
|
||||
}
|
||||
}
|
@ -13,122 +13,108 @@ namespace Tank.CollectionGenericObjects;
|
||||
public class StorageCollection<T>
|
||||
where T : DrawningMachine
|
||||
{
|
||||
/// <summary>
|
||||
/// Словарь (хранилище) с коллекциями
|
||||
/// </summary>
|
||||
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
|
||||
|
||||
/// <summary>
|
||||
/// Возвращение списка названий коллекций
|
||||
/// </summary>
|
||||
public List<string> Keys => _storages.Keys.ToList();
|
||||
|
||||
/// <summary>
|
||||
/// Ключевое слово, с которого должен начинаться файл
|
||||
/// </summary>
|
||||
private readonly string _collectionKey = "CollectionStorage";
|
||||
|
||||
/// <summary>
|
||||
/// Разделитель для записи ключа и значения элемента словаря
|
||||
/// </summary>
|
||||
private readonly string _separatorForKeyValue = "|";
|
||||
|
||||
/// <summary>
|
||||
/// Разделитель для записей коллекции данных в файл
|
||||
/// </summary>
|
||||
private readonly string _separatorItems = ";";
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public StorageCollection()
|
||||
{
|
||||
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление коллекции в хранилище
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <param name="collectionType">тип коллекции</param>
|
||||
public void AddCollection(string name, CollectionType collectionType)
|
||||
{
|
||||
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
|
||||
// TODO Прописать логику для добавления
|
||||
if (name == null || _storages.ContainsKey(name))
|
||||
return;
|
||||
switch (collectionType)
|
||||
{
|
||||
case CollectionType.None:
|
||||
return;
|
||||
case CollectionType.Massive:
|
||||
_storages[name] = new MassiveGenericObjects<T>();
|
||||
return;
|
||||
case CollectionType.List:
|
||||
_storages[name] = new ListGenericObjects<T>();
|
||||
return;
|
||||
}
|
||||
/// <summary>
|
||||
/// Словарь (хранилище) с коллекциями
|
||||
/// </summary>
|
||||
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
|
||||
/// <summary>
|
||||
/// Возвращение списка названий коллекций
|
||||
/// </summary>
|
||||
public List<CollectionInfo> Keys => _storages.Keys.ToList();
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public StorageCollection()
|
||||
{
|
||||
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление коллекции в хранилище
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <param name="collectionType">тип коллекции</param>
|
||||
public void AddCollection(string name, CollectionType collectionType)
|
||||
{
|
||||
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
|
||||
if (_storages.ContainsKey(collectionInfo)) return;
|
||||
if (collectionType == CollectionType.None) return;
|
||||
else if (collectionType == CollectionType.Massive)
|
||||
_storages[collectionInfo] = new MassiveGenericObjects<T>();
|
||||
else if (collectionType == CollectionType.List)
|
||||
_storages[collectionInfo] = new ListGenericObjects<T>();
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
public void DelCollection(string name)
|
||||
{
|
||||
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
|
||||
if (_storages.ContainsKey(collectionInfo))
|
||||
_storages.Remove(collectionInfo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
public void DelCollection(string name)
|
||||
/// <summary>
|
||||
/// Доступ к коллекции
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <returns></returns>
|
||||
public ICollectionGenericObjects<T> this[string name]
|
||||
{
|
||||
get
|
||||
{
|
||||
// TODO Прописать логику для удаления коллекции
|
||||
if (_storages.ContainsKey(name))
|
||||
_storages.Remove(name);
|
||||
}
|
||||
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
|
||||
|
||||
/// <summary>
|
||||
/// Доступ к коллекции
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <returns></returns>
|
||||
public ICollectionGenericObjects<T>? this[string name]
|
||||
{
|
||||
get
|
||||
{
|
||||
// TODO Продумать логику получения объекта
|
||||
if (name == null || !_storages.ContainsKey(name))
|
||||
return null;
|
||||
return _storages[name];
|
||||
}
|
||||
}
|
||||
if (_storages.ContainsKey(collectionInfo))
|
||||
return _storages[collectionInfo];
|
||||
|
||||
/// <summary>
|
||||
/// Сохранение информации по самолетам в хранилище в файл
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
||||
public void SaveData(string filename)
|
||||
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 void SaveData(string filename)
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
|
||||
}
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
File.Delete(filename);
|
||||
}
|
||||
using (StreamWriter writer = new StreamWriter(filename))
|
||||
{
|
||||
writer.Write(_collectionKey);
|
||||
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
|
||||
{
|
||||
throw new InvalidDataException("В хранилище отсутствуют коллекции для сохранения");
|
||||
}
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
File.Delete(filename);
|
||||
}
|
||||
using FileStream fs = new(filename, FileMode.Create);
|
||||
using StreamWriter sw = new StreamWriter(fs);
|
||||
sw.WriteLine(_collectionKey);
|
||||
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
|
||||
{
|
||||
sw.Write(Environment.NewLine);
|
||||
// не сохраняем пустые коллекции
|
||||
StringBuilder sb = new();
|
||||
sb.Append(Environment.NewLine);
|
||||
if (value.Value.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
sw.Write(value.Key);
|
||||
sw.Write(_separatorForKeyValue);
|
||||
sw.Write(value.Value.GetCollectionType);
|
||||
sw.Write(_separatorForKeyValue);
|
||||
sw.Write(value.Value.MaxCount);
|
||||
sw.Write(_separatorForKeyValue);
|
||||
|
||||
sb.Append(value.Key);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
sb.Append(value.Value.MaxCount);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
foreach (T? item in value.Value.GetItems())
|
||||
{
|
||||
string data = item?.GetDataForSave() ?? string.Empty;
|
||||
@ -136,90 +122,87 @@ public class StorageCollection<T>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
sw.Write(data);
|
||||
sw.Write(_separatorItems);
|
||||
sb.Append(data);
|
||||
sb.Append(_separatorItems);
|
||||
}
|
||||
writer.Write(sb);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Загрузка информации по самолетам в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
||||
public void LoadData(string filename)
|
||||
}
|
||||
/// <summary>
|
||||
/// Загрузка информации по автомобилям в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке
|
||||
///данных</returns>
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
throw new FileNotFoundException("Файл не существует");
|
||||
}
|
||||
|
||||
using (StreamReader reader = new(filename))
|
||||
throw new Exception("Файл не существует");
|
||||
}
|
||||
using (StreamReader fs = File.OpenText(filename))
|
||||
{
|
||||
string line = reader.ReadLine();
|
||||
if (line == null || line.Length == 0)
|
||||
string str = fs.ReadLine();
|
||||
if (str == null || str.Length == 0)
|
||||
{
|
||||
throw new InvalidDataException("В файле нет данных");
|
||||
throw new Exception("В файле нет данных");
|
||||
}
|
||||
if (!line.Equals(_collectionKey))
|
||||
if (!str.StartsWith(_collectionKey))
|
||||
{
|
||||
throw new InvalidOperationException("В файле неверные данные");
|
||||
throw new Exception("В файле неверные данные");
|
||||
}
|
||||
_storages.Clear();
|
||||
while ((line = reader.ReadLine()) != null)
|
||||
string strs = "";
|
||||
while ((strs = fs.ReadLine()) != null)
|
||||
{
|
||||
string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 4)
|
||||
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 3)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
|
||||
|
||||
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType);
|
||||
if (collection == null)
|
||||
{
|
||||
throw new InvalidOperationException("Не удалось создать коллекцию");
|
||||
throw new Exception("Не удалось создать коллекцию");
|
||||
}
|
||||
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
|
||||
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
collection.MaxCount = Convert.ToInt32(record[1]);
|
||||
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawningMachine() is T locomotive)
|
||||
if (elem?.CreateDrawningMachine() is T machine)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (collection.Insert(locomotive) == -1)
|
||||
if (collection.Insert(machine) == -1)
|
||||
{
|
||||
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException("Коллекция переполнена", ex);
|
||||
throw new Exception("Коллекция переполнена", ex);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
_storages.Add(record[0], collection);
|
||||
_storages.Add(collectionInfo, collection);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создание коллекции по типу
|
||||
/// </summary>
|
||||
/// <param name="collectionType"></param>
|
||||
/// <returns></returns>
|
||||
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
|
||||
/// <summary>
|
||||
/// Создание коллекции по типу
|
||||
/// </summary>
|
||||
/// <param name="collectionType"></param>
|
||||
/// <returns></returns>
|
||||
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
|
||||
{
|
||||
return collectionType switch
|
||||
{
|
||||
return collectionType switch
|
||||
{
|
||||
CollectionType.Massive => new MassiveGenericObjects<T>(),
|
||||
CollectionType.List => new ListGenericObjects<T>(),
|
||||
_ => null
|
||||
};
|
||||
}
|
||||
CollectionType.Massive => new MassiveGenericObjects<T>(),
|
||||
CollectionType.List => new ListGenericObjects<T>(),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
61
Tank/Tank/Drowings/DrawiningMachineEqutables.cs
Normal file
61
Tank/Tank/Drowings/DrawiningMachineEqutables.cs
Normal file
@ -0,0 +1,61 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using Tank.Entities;
|
||||
|
||||
namespace Tank.Drowings;
|
||||
|
||||
public class DrawiningMachineEqutables : IEqualityComparer<DrawningMachine?>
|
||||
{
|
||||
public bool Equals(DrawningMachine? x, DrawningMachine? y)
|
||||
{
|
||||
if (x == null || x.EntityMachine == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (y == null || y.EntityMachine == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.GetType().Name != y.GetType().Name)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.EntityMachine.Speed != y.EntityMachine.Speed)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.EntityMachine.Weight != y.EntityMachine.Weight)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.EntityMachine.BodyColor != y.EntityMachine.BodyColor)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x is DrawningTank && y is DrawningTank)
|
||||
{
|
||||
EntityTank _x = (EntityTank)x.EntityMachine;
|
||||
EntityTank _y = (EntityTank)x.EntityMachine;
|
||||
if (_x.AdditionalColor != _y.AdditionalColor)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (_x.Pulemet != _y.Pulemet)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (_x.Gusenica != _y.Gusenica)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (_x.Pushka != _y.Pushka)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
public int GetHashCode([DisallowNull] DrawningMachine obj)
|
||||
{
|
||||
return obj.GetHashCode();
|
||||
}
|
||||
}
|
34
Tank/Tank/Drowings/DrawningMachineCompareByColor.cs
Normal file
34
Tank/Tank/Drowings/DrawningMachineCompareByColor.cs
Normal file
@ -0,0 +1,34 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Tank.Drowings;
|
||||
|
||||
public class DrawningMachineCompareByColor : IComparer<DrawningMachine?>
|
||||
{
|
||||
public int Compare(DrawningMachine? x, DrawningMachine? y)
|
||||
{
|
||||
if (x == null || x.EntityMachine == null)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (y == null || y.EntityMachine == null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
var bodycolorCompare = x.EntityMachine.BodyColor.Name.CompareTo(y.EntityMachine.BodyColor.Name);
|
||||
if (bodycolorCompare != 0)
|
||||
{
|
||||
return bodycolorCompare;
|
||||
}
|
||||
var speedCompare = x.EntityMachine.Speed.CompareTo(y.EntityMachine.Speed);
|
||||
if (speedCompare != 0)
|
||||
{
|
||||
return speedCompare;
|
||||
}
|
||||
return x.EntityMachine.Weight.CompareTo(y.EntityMachine.Weight);
|
||||
}
|
||||
}
|
33
Tank/Tank/Drowings/DrawningMachineCompareByType .cs
Normal file
33
Tank/Tank/Drowings/DrawningMachineCompareByType .cs
Normal file
@ -0,0 +1,33 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Tank.Drowings;
|
||||
|
||||
public class DrawningMachineCompareByType : IComparer<DrawningMachine?>
|
||||
{
|
||||
public int Compare(DrawningMachine? x, DrawningMachine? y)
|
||||
{
|
||||
if (x == null || x.EntityMachine == null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
if (y == null || y.EntityMachine == null)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
if (x.GetType().Name != y.GetType().Name)
|
||||
{
|
||||
return x.GetType().Name.CompareTo(y.GetType().Name);
|
||||
}
|
||||
var speedCompare = x.EntityMachine.Speed.CompareTo(y.EntityMachine.Speed);
|
||||
if (speedCompare != 0)
|
||||
{
|
||||
return speedCompare;
|
||||
}
|
||||
return x.EntityMachine.Weight.CompareTo(y.EntityMachine.Weight);
|
||||
}
|
||||
|
||||
}
|
56
Tank/Tank/FormTankCollection.Designer.cs
generated
56
Tank/Tank/FormTankCollection.Designer.cs
generated
@ -30,6 +30,8 @@
|
||||
{
|
||||
groupBoxTools = new GroupBox();
|
||||
panelCompanyTools = new Panel();
|
||||
buttonSortByType = new Button();
|
||||
buttonSortByColor = new Button();
|
||||
buttonAddTank = new Button();
|
||||
maskedTextBoxPosition = new MaskedTextBox();
|
||||
buttonRefresh = new Button();
|
||||
@ -66,15 +68,17 @@
|
||||
groupBoxTools.Controls.Add(panelStorage);
|
||||
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
|
||||
groupBoxTools.Dock = DockStyle.Right;
|
||||
groupBoxTools.Location = new Point(1182, 40);
|
||||
groupBoxTools.Location = new Point(1182, 42);
|
||||
groupBoxTools.Name = "groupBoxTools";
|
||||
groupBoxTools.Size = new Size(371, 990);
|
||||
groupBoxTools.Size = new Size(371, 988);
|
||||
groupBoxTools.TabIndex = 0;
|
||||
groupBoxTools.TabStop = false;
|
||||
groupBoxTools.Text = "Инструменты";
|
||||
//
|
||||
// panelCompanyTools
|
||||
//
|
||||
panelCompanyTools.Controls.Add(buttonSortByType);
|
||||
panelCompanyTools.Controls.Add(buttonSortByColor);
|
||||
panelCompanyTools.Controls.Add(buttonAddTank);
|
||||
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
|
||||
panelCompanyTools.Controls.Add(buttonRefresh);
|
||||
@ -82,17 +86,39 @@
|
||||
panelCompanyTools.Controls.Add(buttonGoToCheck);
|
||||
panelCompanyTools.Dock = DockStyle.Bottom;
|
||||
panelCompanyTools.Enabled = false;
|
||||
panelCompanyTools.Location = new Point(3, 677);
|
||||
panelCompanyTools.Location = new Point(3, 639);
|
||||
panelCompanyTools.Name = "panelCompanyTools";
|
||||
panelCompanyTools.Size = new Size(365, 310);
|
||||
panelCompanyTools.Size = new Size(365, 346);
|
||||
panelCompanyTools.TabIndex = 9;
|
||||
//
|
||||
// buttonSortByType
|
||||
//
|
||||
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonSortByType.Location = new Point(33, 115);
|
||||
buttonSortByType.Name = "buttonSortByType";
|
||||
buttonSortByType.Size = new Size(307, 38);
|
||||
buttonSortByType.TabIndex = 8;
|
||||
buttonSortByType.Text = "Сортировка по типу";
|
||||
buttonSortByType.UseVisualStyleBackColor = true;
|
||||
buttonSortByType.Click += ButtonSortByType_Click;
|
||||
//
|
||||
// buttonSortByColor
|
||||
//
|
||||
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonSortByColor.Location = new Point(33, 70);
|
||||
buttonSortByColor.Name = "buttonSortByColor";
|
||||
buttonSortByColor.Size = new Size(307, 39);
|
||||
buttonSortByColor.TabIndex = 7;
|
||||
buttonSortByColor.Text = "Сортировка по цвету";
|
||||
buttonSortByColor.UseVisualStyleBackColor = true;
|
||||
buttonSortByColor.Click += ButtonSortByColor_Click;
|
||||
//
|
||||
// buttonAddTank
|
||||
//
|
||||
buttonAddTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonAddTank.Location = new Point(33, 3);
|
||||
buttonAddTank.Name = "buttonAddTank";
|
||||
buttonAddTank.Size = new Size(307, 50);
|
||||
buttonAddTank.Size = new Size(307, 41);
|
||||
buttonAddTank.TabIndex = 1;
|
||||
buttonAddTank.Text = "Добавление танка";
|
||||
buttonAddTank.UseVisualStyleBackColor = true;
|
||||
@ -100,17 +126,17 @@
|
||||
//
|
||||
// maskedTextBoxPosition
|
||||
//
|
||||
maskedTextBoxPosition.Location = new Point(33, 126);
|
||||
maskedTextBoxPosition.Location = new Point(33, 159);
|
||||
maskedTextBoxPosition.Mask = "00";
|
||||
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
|
||||
maskedTextBoxPosition.Size = new Size(1116, 39);
|
||||
maskedTextBoxPosition.Size = new Size(307, 39);
|
||||
maskedTextBoxPosition.TabIndex = 3;
|
||||
maskedTextBoxPosition.ValidatingType = typeof(int);
|
||||
//
|
||||
// buttonRefresh
|
||||
//
|
||||
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonRefresh.Location = new Point(33, 263);
|
||||
buttonRefresh.Location = new Point(33, 299);
|
||||
buttonRefresh.Name = "buttonRefresh";
|
||||
buttonRefresh.Size = new Size(307, 38);
|
||||
buttonRefresh.TabIndex = 6;
|
||||
@ -121,7 +147,7 @@
|
||||
// buttonDelTank
|
||||
//
|
||||
buttonDelTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonDelTank.Location = new Point(33, 171);
|
||||
buttonDelTank.Location = new Point(33, 204);
|
||||
buttonDelTank.Name = "buttonDelTank";
|
||||
buttonDelTank.Size = new Size(307, 39);
|
||||
buttonDelTank.TabIndex = 4;
|
||||
@ -132,7 +158,7 @@
|
||||
// buttonGoToCheck
|
||||
//
|
||||
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonGoToCheck.Location = new Point(33, 216);
|
||||
buttonGoToCheck.Location = new Point(33, 249);
|
||||
buttonGoToCheck.Name = "buttonGoToCheck";
|
||||
buttonGoToCheck.Size = new Size(307, 44);
|
||||
buttonGoToCheck.TabIndex = 5;
|
||||
@ -247,9 +273,9 @@
|
||||
// pictureBox
|
||||
//
|
||||
pictureBox.Dock = DockStyle.Fill;
|
||||
pictureBox.Location = new Point(0, 40);
|
||||
pictureBox.Location = new Point(0, 42);
|
||||
pictureBox.Name = "pictureBox";
|
||||
pictureBox.Size = new Size(1182, 990);
|
||||
pictureBox.Size = new Size(1182, 988);
|
||||
pictureBox.TabIndex = 1;
|
||||
pictureBox.TabStop = false;
|
||||
//
|
||||
@ -259,7 +285,7 @@
|
||||
menuStrip1.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
|
||||
menuStrip1.Location = new Point(0, 0);
|
||||
menuStrip1.Name = "menuStrip1";
|
||||
menuStrip1.Size = new Size(1553, 40);
|
||||
menuStrip1.Size = new Size(1553, 42);
|
||||
menuStrip1.TabIndex = 2;
|
||||
menuStrip1.Text = "menuStrip1";
|
||||
//
|
||||
@ -267,7 +293,7 @@
|
||||
//
|
||||
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
|
||||
файлToolStripMenuItem.Name = "файлToolStripMenuItem";
|
||||
файлToolStripMenuItem.Size = new Size(90, 36);
|
||||
файлToolStripMenuItem.Size = new Size(90, 38);
|
||||
файлToolStripMenuItem.Text = "Файл";
|
||||
//
|
||||
// saveToolStripMenuItem
|
||||
@ -343,5 +369,7 @@
|
||||
private ToolStripMenuItem loadToolStripMenuItem;
|
||||
private SaveFileDialog saveFileDialog;
|
||||
private OpenFileDialog openFileDialog;
|
||||
private Button buttonSortByType;
|
||||
private Button buttonSortByColor;
|
||||
}
|
||||
}
|
@ -76,7 +76,7 @@ public partial class FormTankCollection : Form
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (_company + machine != -1)
|
||||
if (_company + machine)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
@ -128,7 +128,7 @@ public partial class FormTankCollection : Form
|
||||
listBoxCollection.Items.Clear();
|
||||
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
|
||||
{
|
||||
string? colName = _storageCollection.Keys?[i];
|
||||
string? colName = _storageCollection.Keys?[i].Name;
|
||||
if (!string.IsNullOrEmpty(colName))
|
||||
{
|
||||
listBoxCollection.Items.Add(colName);
|
||||
@ -175,12 +175,12 @@ public partial class FormTankCollection : Form
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Перерисовка коллекции
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonRefresh_Click(object sender, EventArgs e)
|
||||
/// <summary>
|
||||
/// Перерисовка коллекции
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonRefresh_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
@ -332,4 +332,30 @@ private void ButtonRefresh_Click(object sender, EventArgs e)
|
||||
}
|
||||
}
|
||||
}
|
||||
private void ButtonSortByType_Click(object sender, EventArgs e)
|
||||
{
|
||||
CompareMachines(new DrawningMachineCompareByType());
|
||||
}
|
||||
/// <summary>
|
||||
/// Сортировка по цвету
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonSortByColor_Click(object sender, EventArgs e)
|
||||
{
|
||||
CompareMachines(new DrawningMachineCompareByColor());
|
||||
}
|
||||
/// <summary>
|
||||
/// Сортировка по сравнителю
|
||||
/// </summary>
|
||||
/// <param name="comparer">Сравнитель объектов</param>
|
||||
private void CompareMachines(IComparer<DrawningMachine?> comparer)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_company.Sort(comparer);
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user