LabWork_8
This commit is contained in:
parent
27bea46f7e
commit
297b3a5395
@ -1,5 +1,6 @@
|
||||
using ProjectTank.Drawning;
|
||||
using ProjectTank.CollectionGenericObjects;
|
||||
using ProjectTank.Drawnings;
|
||||
|
||||
/// <summary>
|
||||
/// Абстракция компании, хранящий Танковую базу
|
||||
@ -58,7 +59,7 @@ public abstract class AbstractCompany
|
||||
/// <returns></returns>
|
||||
public static int operator +(AbstractCompany company, DrawningTank tank)
|
||||
{
|
||||
return company?._collection.Insert(tank)??-1;
|
||||
return company._collection?.Insert(tank,new DrawningTankEqutables())??-1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -101,7 +102,11 @@ public abstract class AbstractCompany
|
||||
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сортировка
|
||||
/// </summary>
|
||||
/// <param name="comparer"></param>
|
||||
public void Sort(IComparer<DrawningTank?> comparer) => _collection?.CollectionSort(comparer);
|
||||
/// <summary>
|
||||
/// Вывод заднего фона
|
||||
/// </summary>
|
||||
|
@ -0,0 +1,85 @@
|
||||
|
||||
namespace ProjectTank.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, хранящиий информацию по коллекции
|
||||
/// </summary>
|
||||
public class CollectionInfo : IEquatable<CollectionInfo>
|
||||
{
|
||||
/// <summary>
|
||||
/// Название
|
||||
/// </summary>
|
||||
public string Name { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Тип
|
||||
/// </summary>
|
||||
public CollectionType CollectionType { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Описание
|
||||
/// </summary>
|
||||
public string Description { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Разделитель для записи информации по объекту в файл
|
||||
/// </summary>
|
||||
private static readonly string _separator = "-";
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
/// <param name="name">Название</param>
|
||||
/// <param name="collectionType">Тип</param>
|
||||
/// <param name="description">Описание</param>
|
||||
public CollectionInfo(string name, CollectionType collectionType, string
|
||||
description)
|
||||
{
|
||||
Name = name;
|
||||
CollectionType = collectionType;
|
||||
Description = description;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создание объекта из строки
|
||||
/// </summary>
|
||||
/// <param name="data">Строка</param>
|
||||
/// <returns>Объект или null</returns>
|
||||
public static CollectionInfo? GetCollectionInfo(string data)
|
||||
{
|
||||
string[] strs = data.Split(_separator,
|
||||
StringSplitOptions.RemoveEmptyEntries);
|
||||
if (strs.Length < 1 || strs.Length > 3)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new CollectionInfo(strs[0], (CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ?strs[2] : string.Empty);
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return Name + _separator + CollectionType + _separator + Description;
|
||||
}
|
||||
|
||||
public bool Equals(CollectionInfo? other)
|
||||
{
|
||||
return Name == other?.Name;
|
||||
}
|
||||
|
||||
public override bool Equals(object? obj)
|
||||
{
|
||||
return Equals(obj as CollectionInfo);
|
||||
}
|
||||
|
||||
public bool IsEmpty()
|
||||
{
|
||||
if (string.IsNullOrEmpty(Name) && CollectionType != CollectionType.None) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
return Name.GetHashCode();
|
||||
}
|
||||
}
|
@ -1,4 +1,6 @@
|
||||
namespace ProjectTank.CollectionGenericObjects
|
||||
using ProjectTank.Drawning;
|
||||
|
||||
namespace ProjectTank.CollectionGenericObjects
|
||||
{
|
||||
/// <summary>
|
||||
/// Интерфейс описания действий для набора хранимых данных
|
||||
@ -21,16 +23,18 @@
|
||||
/// Добавление объекта в коллекцию
|
||||
/// </summary>
|
||||
/// <param name="obj">Добавляемый объект</param>
|
||||
/// <param name="comparer">Сравнение двух объектов</param>
|
||||
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
|
||||
int Insert(T obj);
|
||||
int Insert(T obj, IEqualityComparer<T?>? comparer = null);
|
||||
|
||||
/// <summary>
|
||||
/// Добавление объекта в коллекцию на конкретную позицию
|
||||
/// </summary>
|
||||
/// <param name="obj">Добавляемый объект</param>
|
||||
/// <param name="position">Позиция</param>
|
||||
/// <param name="comparer">Сравнение двух объектов</param>
|
||||
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
|
||||
int Insert(T obj, int position);
|
||||
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
|
||||
|
||||
/// <summary>
|
||||
/// Удаление объекта из коллекции с конкретной позиции
|
||||
@ -56,5 +60,10 @@
|
||||
/// </summary>
|
||||
/// <returns>Поэлементный вывод элементов коллекции</returns>
|
||||
IEnumerable<T?> GetItems();
|
||||
/// <summary>
|
||||
/// Сортировка коллекции
|
||||
/// </summary>
|
||||
/// <param name="comparer"></param>
|
||||
void CollectionSort(IComparer<T?> comparer);
|
||||
}
|
||||
}
|
||||
|
@ -15,7 +15,6 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
/// Список объектов, которые храним
|
||||
/// </summary>
|
||||
private readonly List<T?> _collection;
|
||||
|
||||
/// <summary>
|
||||
/// Максимально допустимое число объектов в списке
|
||||
/// </summary>
|
||||
@ -47,53 +46,43 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
{
|
||||
_collection = new();
|
||||
}
|
||||
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
if (position >= Count || position < 0)
|
||||
{
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
if (_collection[position] == null) throw new ObjectNotFoundException();
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
// TODO проверка, что не превышено максимальное количество элементов
|
||||
if (Count == _maxCount)
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
if (comparer != null)
|
||||
{
|
||||
throw new CollectionOverflowException(Count);
|
||||
if (_collection.Contains(obj, comparer))
|
||||
{
|
||||
throw new ObjectAlreadyExistsException();
|
||||
}
|
||||
}
|
||||
// TODO вставка в конец набора
|
||||
_collection.Add(obj);
|
||||
return _collection.Count;
|
||||
return Count;
|
||||
|
||||
}
|
||||
public int Insert(T obj, int position)
|
||||
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
// TODO проверка, что не превышено максимальное количество элементов
|
||||
if (Count == _maxCount)
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
if (comparer != null)
|
||||
{
|
||||
throw new CollectionOverflowException(Count);
|
||||
if (_collection.Contains(obj, comparer))
|
||||
{
|
||||
throw new ObjectAlreadyExistsException(position);
|
||||
}
|
||||
// TODO проверка позиции
|
||||
if (position >= Count || position < 0)
|
||||
{
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
// TODO вставка по позиции
|
||||
_collection.Insert(position, obj);
|
||||
return position;
|
||||
}
|
||||
public T? Remove(int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
if (position >= Count || position < 0)
|
||||
{
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
// TODO удаление объекта из списка
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
T? obj = _collection[position];
|
||||
_collection.RemoveAt(position);
|
||||
return obj;
|
||||
@ -106,4 +95,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
|
||||
public void CollectionSort(IComparer<T?> comparer)
|
||||
{
|
||||
_collection.Sort(comparer);
|
||||
}
|
||||
}
|
||||
|
@ -12,9 +12,7 @@ using ProjectTank.Exceptions;
|
||||
/// Массив объектов, которые храним
|
||||
/// </summary>
|
||||
private T?[] _collection;
|
||||
|
||||
public int Count => _collection.Length;
|
||||
|
||||
public int MaxCount
|
||||
{
|
||||
get
|
||||
@ -38,7 +36,6 @@ using ProjectTank.Exceptions;
|
||||
}
|
||||
|
||||
public CollectionType GetCollectionType => CollectionType.Massive;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
@ -46,81 +43,78 @@ using ProjectTank.Exceptions;
|
||||
{
|
||||
_collection = Array.Empty<T?>();
|
||||
}
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
if (position < 0 || position > _collection.Length)
|
||||
{
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
if (position >= Count && _collection[position] == null)
|
||||
{
|
||||
throw new ObjectNotFoundException(position);
|
||||
}
|
||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException();
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
if (comparer != null)
|
||||
{
|
||||
foreach (T? i in _collection)
|
||||
{
|
||||
if (comparer.Equals(i, obj))
|
||||
{
|
||||
throw new ObjectAlreadyExistsException(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Insert(obj, 0);
|
||||
throw new CollectionOverflowException(Count);
|
||||
throw new CollectionOverflowException();
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
if (position > _collection.Length || position < 0)
|
||||
if (position < 0 || position >= Count)
|
||||
{
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
throw new PositionOutOfCollectionException();
|
||||
}
|
||||
if (comparer != null)
|
||||
{
|
||||
foreach (T? i in _collection)
|
||||
{
|
||||
if (comparer.Equals(i, obj))
|
||||
{
|
||||
throw new ObjectAlreadyExistsException(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то
|
||||
// ищется свободное место после этой позиции и идет вставка туда
|
||||
// если нет после, ищем до
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
}
|
||||
|
||||
for (int tmp = position + 1; tmp < _collection.Length; tmp++)
|
||||
}
|
||||
int temp = position + 1;
|
||||
while (temp < Count)
|
||||
{
|
||||
if (_collection[tmp] == null)
|
||||
if (_collection[temp] == null)
|
||||
{
|
||||
_collection[tmp] = obj;
|
||||
return tmp;
|
||||
_collection[temp] = obj;
|
||||
return temp;
|
||||
}
|
||||
++temp;
|
||||
}
|
||||
|
||||
for (int tmp = position - 1; tmp >= 0; tmp--)
|
||||
temp = position - 1;
|
||||
while (temp >= 0)
|
||||
{
|
||||
if (_collection[tmp] == null)
|
||||
if (_collection[temp] == null)
|
||||
{
|
||||
_collection[tmp] = obj;
|
||||
return tmp;
|
||||
_collection[temp] = obj;
|
||||
return temp;
|
||||
}
|
||||
--temp;
|
||||
}
|
||||
|
||||
throw new CollectionOverflowException(Count);
|
||||
throw new CollectionOverflowException();
|
||||
}
|
||||
|
||||
public T? Remove(int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
if (position < 0 || position > _collection.Length)
|
||||
{
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
throw new ObjectNotFoundException(position);
|
||||
}
|
||||
T? tmp = _collection[position];
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
|
||||
if (_collection[position] == null) throw new ObjectNotFoundException();
|
||||
T? myObject = _collection[position];
|
||||
_collection[position] = null;
|
||||
// TODO удаление объекта из массива, присвоив элементу массива значение null
|
||||
return tmp;
|
||||
return myObject;
|
||||
}
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
@ -130,4 +124,9 @@ using ProjectTank.Exceptions;
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
|
||||
public void CollectionSort(IComparer<T?> comparer)
|
||||
{
|
||||
Array.Sort(_collection, comparer);
|
||||
}
|
||||
}
|
@ -1,7 +1,8 @@
|
||||
|
||||
using ProjectTank.Drawning;
|
||||
using ProjectTank.Exceptions;
|
||||
using System.Text;
|
||||
using System.Data;
|
||||
|
||||
|
||||
namespace ProjectTank.CollectionGenericObjects
|
||||
{
|
||||
@ -15,16 +16,17 @@ namespace ProjectTank.CollectionGenericObjects
|
||||
/// <summary>
|
||||
/// Словарь (хранилище) с коллекциями
|
||||
/// </summary>
|
||||
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
|
||||
/// <summary>
|
||||
/// Возвращение списка названий коллекций
|
||||
/// </summary>
|
||||
public List<string> Keys => _storages.Keys.ToList();
|
||||
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
|
||||
|
||||
/// <summary>
|
||||
/// Ключевое слово, с которого должен начинаться файл
|
||||
/// </summary>
|
||||
private readonly string _collectionKey = "CollectionStorage";
|
||||
private readonly string _collectionKey = "CollectionsStorage";
|
||||
|
||||
/// <summary>
|
||||
/// Разделитель для записей коллекции данных в файл
|
||||
/// </summary>
|
||||
private readonly string _separatorItems = ";";
|
||||
|
||||
/// <summary>
|
||||
/// Разделитель для записи ключа и значения элемента словаря
|
||||
@ -32,15 +34,16 @@ namespace ProjectTank.CollectionGenericObjects
|
||||
private readonly string _separatorForKeyValue = "|";
|
||||
|
||||
/// <summary>
|
||||
/// Разделитель для записей коллекции данных в файл
|
||||
/// Возвращение списка названий коллекций
|
||||
/// </summary>
|
||||
private readonly string _separatorItems = ";";
|
||||
public List<CollectionInfo> Keys => _storages.Keys.ToList();
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public StorageCollection()
|
||||
{
|
||||
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
|
||||
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление коллекции в хранилище
|
||||
@ -49,33 +52,34 @@ namespace ProjectTank.CollectionGenericObjects
|
||||
/// <param name="collectionType">тип коллекции</param>
|
||||
public void AddCollection(string name, CollectionType collectionType)
|
||||
{
|
||||
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
|
||||
// TODO Прописать логику для добавления
|
||||
if (name == null || _storages.ContainsKey(name))
|
||||
CollectionInfo collectionInfo = new(name, collectionType, string.Empty);
|
||||
if (name == null || _storages.ContainsKey(collectionInfo))
|
||||
return;
|
||||
switch (collectionType)
|
||||
{
|
||||
case CollectionType.None:
|
||||
return;
|
||||
case CollectionType.Massive:
|
||||
_storages[name] = new MassiveGenericObjects<T>();
|
||||
_storages[collectionInfo] = new MassiveGenericObjects<T>();
|
||||
return;
|
||||
case CollectionType.List:
|
||||
_storages[name] = new ListGenericObjects<T>();
|
||||
_storages[collectionInfo] = new ListGenericObjects<T>();
|
||||
return;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
public void DelCollection(string name)
|
||||
{
|
||||
// TODO Прописать логику для удаления коллекции
|
||||
if (_storages.ContainsKey(name))
|
||||
_storages.Remove(name);
|
||||
CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty);
|
||||
if (_storages.ContainsKey(collectionInfo))
|
||||
_storages.Remove(collectionInfo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Доступ к коллекции
|
||||
/// </summary>
|
||||
@ -85,42 +89,43 @@ namespace ProjectTank.CollectionGenericObjects
|
||||
{
|
||||
get
|
||||
{
|
||||
// TODO Продумать логику получения объекта
|
||||
if (name == null || !_storages.ContainsKey(name))
|
||||
CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty);
|
||||
if (_storages.ContainsKey(collectionInfo))
|
||||
return _storages[collectionInfo];
|
||||
return null;
|
||||
return _storages[name];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сохранение информации по лодкам в хранилище в файл
|
||||
/// </summary>
|
||||
/// <param name="filename"></param>
|
||||
/// <returns></returns>
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
{
|
||||
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)
|
||||
using (StreamWriter writer = new(filename))
|
||||
{
|
||||
sw.Write(Environment.NewLine);
|
||||
writer.Write(_collectionKey);
|
||||
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
|
||||
{
|
||||
writer.Write(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);
|
||||
|
||||
writer.Write(value.Key);
|
||||
writer.Write(_separatorForKeyValue);
|
||||
writer.Write(value.Value.MaxCount);
|
||||
writer.Write(_separatorForKeyValue);
|
||||
|
||||
foreach (T? item in value.Value.GetItems())
|
||||
{
|
||||
@ -129,17 +134,17 @@ namespace ProjectTank.CollectionGenericObjects
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
sw.Write(data);
|
||||
sw.Write(_separatorItems);
|
||||
writer.Write(data);
|
||||
writer.Write(_separatorItems);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Загрузка информации по локомотивам в хранилище из файла
|
||||
/// Загрузка информации по лодкам в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <param name="filename">>Путь и имя файла</param>
|
||||
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
@ -147,63 +152,60 @@ namespace ProjectTank.CollectionGenericObjects
|
||||
{
|
||||
throw new FileNotFoundException("Файл не существует");
|
||||
}
|
||||
|
||||
using (StreamReader reader = new(filename))
|
||||
{
|
||||
string line = reader.ReadLine();
|
||||
if (line == null || line.Length == 0)
|
||||
{
|
||||
throw new InvalidDataException("В файле нет данных");
|
||||
throw new ArgumentException("В файле нет данных");
|
||||
}
|
||||
if (!line.Equals(_collectionKey))
|
||||
{
|
||||
throw new InvalidOperationException("В файле неверные данные");
|
||||
throw new InvalidDataException("В файле неверные данные");
|
||||
}
|
||||
_storages.Clear();
|
||||
while ((line = reader.ReadLine()) != null)
|
||||
{
|
||||
string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 4)
|
||||
string[] record = line.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("Не удалось создать коллекцию");
|
||||
}
|
||||
|
||||
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?.CreateDrawningTank() is T locomotive)
|
||||
if (elem?.CreateDrawningTank() is T boat)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (collection.Insert(locomotive) == -1)
|
||||
if (collection.Insert(boat) == -1)
|
||||
{
|
||||
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
throw new ConstraintException("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException("Коллекция переполнена", ex);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
_storages.Add(record[0], collection);
|
||||
throw new DataException("Коллекция переполнена", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
_storages.Add(collectionInfo, collection);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Создание коллекции по типа
|
||||
/// Создание коллекции по типу
|
||||
/// </summary>
|
||||
/// <param name="collectionType"></param>
|
||||
/// <returns></returns>
|
||||
@ -213,7 +215,7 @@ namespace ProjectTank.CollectionGenericObjects
|
||||
{
|
||||
CollectionType.Massive => new MassiveGenericObjects<T>(),
|
||||
CollectionType.List => new ListGenericObjects<T>(),
|
||||
_ => null
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,35 @@
|
||||
namespace ProjectTank.Drawning;
|
||||
|
||||
public class DrawningTankCompareByColor : IComparer<DrawningTank?>
|
||||
{
|
||||
public int Compare(DrawningTank? x, DrawningTank? y)
|
||||
{
|
||||
if (x == null && y == null) return 0;
|
||||
if (x == null || x.EntityTank == null)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (y == null || y.EntityTank== null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (ToHex(x.EntityTank.BodyColor) != ToHex(y.EntityTank.BodyColor))
|
||||
{
|
||||
return String.Compare(ToHex(x.EntityTank.BodyColor), ToHex(y.EntityTank.BodyColor),
|
||||
StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
var speedCompare = x.EntityTank.Speed.CompareTo(y.EntityTank.Speed);
|
||||
if (speedCompare != 0)
|
||||
{
|
||||
return speedCompare;
|
||||
}
|
||||
|
||||
return x.EntityTank.Weight.CompareTo(y.EntityTank.Weight);
|
||||
}
|
||||
static String ToHex(Color c)
|
||||
=> $"#{c.R:X2}{c.G:X2}{c.B:X2}";
|
||||
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
|
||||
using ProjectTank.Drawning;
|
||||
|
||||
namespace ProjectTank.Drawnings;
|
||||
/// <summary>
|
||||
/// Сравнение по типу, скорости и весу
|
||||
/// </summary>
|
||||
public class DrawningTankCompareByType : IComparer<DrawningTank?>
|
||||
{
|
||||
public int Compare(DrawningTank? x, DrawningTank? y)
|
||||
{
|
||||
if (x == null || x.EntityTank == null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
if (y == null || y.EntityTank == null)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
if (x.GetType().Name != y.GetType().Name)
|
||||
{
|
||||
return x.GetType().Name.CompareTo(y.GetType().Name);
|
||||
}
|
||||
|
||||
var speedCompare = x.EntityTank.Speed.CompareTo(y.EntityTank.Speed);
|
||||
if (speedCompare != 0)
|
||||
{
|
||||
return speedCompare;
|
||||
}
|
||||
|
||||
return x.EntityTank.Weight.CompareTo(y.EntityTank.Weight);
|
||||
}
|
||||
}
|
58
ProjectTank/ProjectTank/Drawning/DrawningTankEqutables.cs
Normal file
58
ProjectTank/ProjectTank/Drawning/DrawningTankEqutables.cs
Normal file
@ -0,0 +1,58 @@
|
||||
|
||||
using ProjectTank.Drawning;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
namespace ProjectTank.Drawnings;
|
||||
|
||||
public class DrawningTankEqutables : IEqualityComparer<DrawningTank?>
|
||||
{
|
||||
public bool Equals(DrawningTank? x, DrawningTank? y)
|
||||
{
|
||||
if (x == null || x.EntityTank == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (y == null || y.EntityTank == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.GetType().Name != y.GetType().Name)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.EntityTank.Speed != y.EntityTank.Speed)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.EntityTank.Weight != y.EntityTank.Weight)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.EntityTank.BodyColor != y.EntityTank.BodyColor)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x is DrawningBattleTank && y is DrawningBattleTank)
|
||||
{
|
||||
EntityBattleTank entityX = (EntityBattleTank)x.EntityTank;
|
||||
EntityBattleTank entityY = (EntityBattleTank)y.EntityTank;
|
||||
if (entityX.MachinGun!= entityY.MachinGun)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (entityX.Gun != entityY.Gun)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (entityX.AdditionalColor != entityY.AdditionalColor)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public int GetHashCode([DisallowNull] DrawningTank? obj)
|
||||
{
|
||||
return obj.GetHashCode();
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
|
||||
namespace ProjectTank.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку, что в коллекции уже есть такой элемент
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class ObjectAlreadyExistsException : ApplicationException
|
||||
{
|
||||
public ObjectAlreadyExistsException(object i) : base("В коллекции уже есть такой элемент " + i) { }
|
||||
public ObjectAlreadyExistsException() : base() { }
|
||||
public ObjectAlreadyExistsException(string message) : base(message) { }
|
||||
public ObjectAlreadyExistsException(string message, Exception exception) : base(message, exception)
|
||||
{ }
|
||||
protected ObjectAlreadyExistsException(SerializationInfo info, StreamingContext context) : base(info, context) { }
|
||||
}
|
@ -54,6 +54,8 @@ namespace ProjectTank
|
||||
LoadToolStripMenuItem = new ToolStripMenuItem();
|
||||
saveFileDialog = new SaveFileDialog();
|
||||
openFileDialog = new OpenFileDialog();
|
||||
buttonSortByColor = new Button();
|
||||
buttonSortByType = new Button();
|
||||
groupBoxTools.SuspendLayout();
|
||||
panelCompanyTools.SuspendLayout();
|
||||
panelStorage.SuspendLayout();
|
||||
@ -70,13 +72,15 @@ namespace ProjectTank
|
||||
groupBoxTools.Dock = DockStyle.Right;
|
||||
groupBoxTools.Location = new Point(824, 24);
|
||||
groupBoxTools.Name = "groupBoxTools";
|
||||
groupBoxTools.Size = new Size(187, 623);
|
||||
groupBoxTools.Size = new Size(187, 652);
|
||||
groupBoxTools.TabIndex = 0;
|
||||
groupBoxTools.TabStop = false;
|
||||
groupBoxTools.Text = "инструменты";
|
||||
//
|
||||
// panelCompanyTools
|
||||
//
|
||||
panelCompanyTools.Controls.Add(buttonSortByColor);
|
||||
panelCompanyTools.Controls.Add(buttonSortByType);
|
||||
panelCompanyTools.Controls.Add(buttonAddTank);
|
||||
panelCompanyTools.Controls.Add(maskedTextBox);
|
||||
panelCompanyTools.Controls.Add(buttonRefresh);
|
||||
@ -85,7 +89,7 @@ namespace ProjectTank
|
||||
panelCompanyTools.Enabled = false;
|
||||
panelCompanyTools.Location = new Point(3, 372);
|
||||
panelCompanyTools.Name = "panelCompanyTools";
|
||||
panelCompanyTools.Size = new Size(184, 238);
|
||||
panelCompanyTools.Size = new Size(184, 319);
|
||||
panelCompanyTools.TabIndex = 8;
|
||||
//
|
||||
// buttonAddTank
|
||||
@ -101,7 +105,7 @@ namespace ProjectTank
|
||||
//
|
||||
// maskedTextBox
|
||||
//
|
||||
maskedTextBox.Location = new Point(6, 85);
|
||||
maskedTextBox.Location = new Point(6, 44);
|
||||
maskedTextBox.Mask = "00";
|
||||
maskedTextBox.Name = "maskedTextBox";
|
||||
maskedTextBox.Size = new Size(166, 23);
|
||||
@ -111,7 +115,7 @@ namespace ProjectTank
|
||||
// buttonRefresh
|
||||
//
|
||||
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonRefresh.Location = new Point(3, 200);
|
||||
buttonRefresh.Location = new Point(3, 159);
|
||||
buttonRefresh.Name = "buttonRefresh";
|
||||
buttonRefresh.Size = new Size(166, 35);
|
||||
buttonRefresh.TabIndex = 6;
|
||||
@ -122,7 +126,7 @@ namespace ProjectTank
|
||||
// buttonRemoveTank
|
||||
//
|
||||
buttonRemoveTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonRemoveTank.Location = new Point(3, 114);
|
||||
buttonRemoveTank.Location = new Point(3, 73);
|
||||
buttonRemoveTank.Name = "buttonRemoveTank";
|
||||
buttonRemoveTank.Size = new Size(169, 35);
|
||||
buttonRemoveTank.TabIndex = 4;
|
||||
@ -133,9 +137,9 @@ namespace ProjectTank
|
||||
// buttonGoToCheck
|
||||
//
|
||||
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonGoToCheck.Location = new Point(6, 159);
|
||||
buttonGoToCheck.Location = new Point(6, 118);
|
||||
buttonGoToCheck.Name = "buttonGoToCheck";
|
||||
buttonGoToCheck.Size = new Size(159, 35);
|
||||
buttonGoToCheck.Size = new Size(166, 35);
|
||||
buttonGoToCheck.TabIndex = 5;
|
||||
buttonGoToCheck.Text = "Передать на тесты";
|
||||
buttonGoToCheck.UseVisualStyleBackColor = true;
|
||||
@ -250,7 +254,7 @@ namespace ProjectTank
|
||||
pictureBox.Dock = DockStyle.Fill;
|
||||
pictureBox.Location = new Point(0, 24);
|
||||
pictureBox.Name = "pictureBox";
|
||||
pictureBox.Size = new Size(824, 623);
|
||||
pictureBox.Size = new Size(824, 652);
|
||||
pictureBox.TabIndex = 1;
|
||||
pictureBox.TabStop = false;
|
||||
//
|
||||
@ -294,11 +298,33 @@ namespace ProjectTank
|
||||
//
|
||||
openFileDialog.Filter = "txt file | *.txt";
|
||||
//
|
||||
// buttonSortByColor
|
||||
//
|
||||
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonSortByColor.Location = new Point(3, 241);
|
||||
buttonSortByColor.Name = "buttonSortByColor";
|
||||
buttonSortByColor.Size = new Size(166, 35);
|
||||
buttonSortByColor.TabIndex = 8;
|
||||
buttonSortByColor.Text = "Сортировка по цвету";
|
||||
buttonSortByColor.UseVisualStyleBackColor = true;
|
||||
buttonSortByColor.Click += buttonSortByColor_Click;
|
||||
//
|
||||
// buttonSortByType
|
||||
//
|
||||
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonSortByType.Location = new Point(3, 200);
|
||||
buttonSortByType.Name = "buttonSortByType";
|
||||
buttonSortByType.Size = new Size(166, 35);
|
||||
buttonSortByType.TabIndex = 7;
|
||||
buttonSortByType.Text = "Сортировка по типу";
|
||||
buttonSortByType.UseVisualStyleBackColor = true;
|
||||
buttonSortByType.Click += buttonSortByType_Click;
|
||||
//
|
||||
// FormBattleTankCollection
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(7F, 15F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(1011, 647);
|
||||
ClientSize = new Size(1011, 676);
|
||||
Controls.Add(pictureBox);
|
||||
Controls.Add(groupBoxTools);
|
||||
Controls.Add(menuStrip);
|
||||
@ -345,5 +371,7 @@ namespace ProjectTank
|
||||
private ToolStripMenuItem LoadToolStripMenuItem;
|
||||
private SaveFileDialog saveFileDialog;
|
||||
private OpenFileDialog openFileDialog;
|
||||
private Button buttonSortByColor;
|
||||
private Button buttonSortByType;
|
||||
}
|
||||
}
|
@ -1,6 +1,7 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProjectTank.CollectionGenericObjects;
|
||||
using ProjectTank.Drawning;
|
||||
using ProjectTank.Drawnings;
|
||||
using ProjectTank.Exceptions;
|
||||
|
||||
namespace ProjectTank
|
||||
@ -72,6 +73,11 @@ namespace ProjectTank
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
catch (ObjectAlreadyExistsException)
|
||||
{
|
||||
MessageBox.Show("Такой объект уже существует");
|
||||
_logger.LogError("Ошибка: такой объект уже существует {0}", tank);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -247,7 +253,7 @@ namespace ProjectTank
|
||||
listBoxСollection.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))
|
||||
{
|
||||
listBoxСollection.Items.Add(colName);
|
||||
@ -327,5 +333,24 @@ namespace ProjectTank
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void buttonSortByType_Click(object sender, EventArgs e)
|
||||
{
|
||||
CompareTank(new DrawningTankCompareByType());
|
||||
}
|
||||
|
||||
private void buttonSortByColor_Click(object sender, EventArgs e)
|
||||
{
|
||||
CompareTank(new DrawningTankCompareByColor());
|
||||
}
|
||||
private void CompareTank(IComparer<DrawningTank?> comparer)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_company.Sort(comparer);
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user