PIbd-11 Kudyaeva.V.A LabWork08 Simple #9

Closed
Kudyaeva wants to merge 1 commits from LabWork08 into LabWork07
13 changed files with 452 additions and 120 deletions

View File

@ -59,7 +59,7 @@ public abstract class AbstractCompany
/// <returns></returns> /// <returns></returns>
public static int operator +(AbstractCompany company, DrawningPropelledArtillery propelledartillery) public static int operator +(AbstractCompany company, DrawningPropelledArtillery propelledartillery)
{ {
return company._collection.Insert(propelledartillery); return company._collection.Insert(propelledartillery, new DrawiningPropelledArtilleryEqutables());
} }
/// <summary> /// <summary>
@ -114,4 +114,11 @@ public abstract class AbstractCompany
/// Расстановка объектов /// Расстановка объектов
/// </summary> /// </summary>
protected abstract void SetObjectsPosition(); protected abstract void SetObjectsPosition();
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningPropelledArtillery?> comparer) => _collection?.CollectionSort(comparer);
} }

View File

@ -0,0 +1,83 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.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 override int GetHashCode()
{
return Name.GetHashCode();
}
}

View File

@ -1,4 +1,5 @@
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects; 
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
/// <summary> /// <summary>
/// Параметризованный набор объектов /// Параметризованный набор объектов
@ -14,20 +15,22 @@ public interface ICollectionGenericObjects<T>
/// <summary> /// <summary>
/// Установка максимального количества элементов /// Установка максимального количества элементов
/// </summary> /// </summary>
int MaxCount { get; set; } int MaxCount { set; get; }
/// <summary> /// <summary>
/// Добавление объекта в коллекцию /// Добавление объекта в коллекцию
/// </summary> /// </summary>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// /// <param name="comparer">Cравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка неудалась</returns> /// <returns>true - вставка прошла удачно, false - вставка неудалась</returns>
int Insert(T obj); int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary> /// <summary>
/// Добавление объекта в коллекцию на конкретную позицию /// Добавление объекта в коллекцию на конкретную позицию
/// </summary> /// </summary>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <param name="comparer">Cравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка неудалась</returns> /// <returns>true - вставка прошла удачно, false - вставка неудалась</returns>
int Insert(T obj, int position); int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary> /// <summary>
/// Удаление объекта из коллекции с конкретной позиции /// Удаление объекта из коллекции с конкретной позиции
/// </summary> /// </summary>
@ -49,4 +52,9 @@ public interface ICollectionGenericObjects<T>
/// </summary> /// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns> /// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems(); IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
} }

View File

@ -1,78 +1,93 @@
using SelfPropelledArtilleryUnit.Exceptions; using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.Exceptions;
using System.Collections.Generic;
using System.Linq;
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects; namespace SelfPropelledArtilleryUnit.CollectionGenericObjects
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{ {
/// <summary> public class ListGenericObjects<T> : ICollectionGenericObjects<T>
/// Список объектов, которые храним where T : class
/// </summary>
private readonly List<T?> _collection;
/// <summary>
/// Максимально допустимое число объектов в списке
/// </summary>
private int _maxCount;
public int Count => _collection.Count;
public int MaxCount
{ {
get /// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T?> _collection;
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Максимально допустимое число объектов в списке
/// </summary>
private int _maxCount;
public int Count => _collection.Count;
public int MaxCount
{ {
return Count; get
}
set
{
if (value > 0)
{ {
_maxCount = value; return Count;
}
set
{
if (value > 0)
{
_maxCount = value;
}
} }
} }
} /// <summary>
/// Конструктор
public CollectionType GetCollectionType => CollectionType.List; /// </summary>
/// <summary> public ListGenericObjects()
/// Конструктор
/// </summary>
public ListGenericObjects()
{
_collection = new();
}
public T? Get(int position)
{
//TODO выброс ошибки если выход за границу
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
{
// TODO выброс ошибки если переполнение
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
// TODO выброс ошибки если переполнение
// TODO выброс ошибки если за границу
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return position;
}
public T Remove(int position)
{
//TODO если выброс за границу
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position];
_collection.RemoveAt(position);
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; ++i)
{ {
yield return _collection[i]; _collection = new();
}
public T? Get(int position)
{
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectIsEqualException();
}
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectIsEqualException();
}
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return position;
}
public T Remove(int position)
{
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position];
_collection.RemoveAt(position);
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; ++i)
{
yield return _collection[i];
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
} }
} }
} }

View File

@ -1,4 +1,5 @@
using SelfPropelledArtilleryUnit.Exceptions; using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.Exceptions;
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects; namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
@ -36,21 +37,29 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
} }
} }
/// <summary>
/// Конструктор
/// </summary>
public MassiveGenericObjects() public MassiveGenericObjects()
{ {
_collection = Array.Empty<T?>(); _collection = Array.Empty<T?>();
} }
public T Get(int position) public T Get(int position)
{ {
// TODO выброс ошибки если выход за границу
// TODO выброс ошибки если объект пустой
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position); if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{ {
// TODO выброс ошибки если переполнение if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningPropelledArtillery>).Equals(obj as DrawningPropelledArtillery, item as DrawningPropelledArtillery))
throw new ObjectIsEqualException();
}
}
int index = 0; int index = 0;
while (index < _collection.Length) while (index < _collection.Length)
{ {
@ -63,10 +72,16 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
throw new CollectionOverflowException(Count); throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{ {
// TODO выброс ошибки если переполнение if (comparer != null)
// TODO выброс ошибки если выход за границу {
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningPropelledArtillery>).Equals(obj as DrawningPropelledArtillery, item as DrawningPropelledArtillery))
throw new ObjectIsEqualException();
}
}
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) if (_collection[position] == null)
{ {
@ -97,8 +112,6 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
public T Remove(int position) public T Remove(int position)
{ {
// TODO выброс ошибки если выход за границу
// TODO выброс ошибки если объект пустой
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position); if (_collection[position] == null) throw new ObjectNotFoundException(position);
T obj = _collection[position]; T obj = _collection[position];
@ -112,4 +125,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
} }

View File

@ -1,5 +1,6 @@
using SelfPropelledArtilleryUnit.Drawnings; using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.Exceptions; using SelfPropelledArtilleryUnit.Exceptions;
using System.Collections.Generic;
using System.Text; using System.Text;
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects; namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
@ -9,18 +10,18 @@ public class StorageCollection<T>
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages; readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary> /// <summary>
/// Возвращение списка названий коллекций /// Возвращение списка названий коллекций
/// </summary> /// </summary>
public List<string> Keys => _storages.Keys.ToList(); public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
} }
/// <summary> /// <summary>
/// Добавление коллекции в хранилище /// Добавление коллекции в хранилище
@ -29,14 +30,13 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param> /// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(string name, CollectionType collectionType)
{ {
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
// TODO Прописать логику для добавления if (_storages.ContainsKey(collectionInfo)) return;
if (_storages.ContainsKey(name)) return;
if (collectionType == CollectionType.None) return; if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive) else if (collectionType == CollectionType.Massive)
_storages[name] = new MassiveGenericObjects<T>(); _storages[collectionInfo] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List) else if (collectionType == CollectionType.List)
_storages[name] = new ListGenericObjects<T>(); _storages[collectionInfo] = new ListGenericObjects<T>();
} }
/// <summary> /// <summary>
/// Удаление коллекции /// Удаление коллекции
@ -44,10 +44,9 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
public void DelCollection(string name) public void DelCollection(string name)
{ {
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
// TODO Прописать логику для удаления коллекции if (_storages.ContainsKey(collectionInfo))
if (_storages.ContainsKey(name)) _storages.Remove(collectionInfo);
_storages.Remove(name);
} }
/// <summary> /// <summary>
/// Доступ к коллекции /// Доступ к коллекции
@ -58,9 +57,9 @@ public class StorageCollection<T>
{ {
get get
{ {
// TODO Продумать логику получения объекта CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(name)) if (_storages.ContainsKey(collectionInfo))
return _storages[name]; return _storages[collectionInfo];
return null; return null;
} }
} }
@ -93,7 +92,7 @@ public class StorageCollection<T>
using (StreamWriter writer = new StreamWriter(filename)) using (StreamWriter writer = new StreamWriter(filename))
{ {
writer.Write(_collectionKey); writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages) foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{ {
writer.Write(Environment.NewLine); writer.Write(Environment.NewLine);
// не сохраняем пустые коллекции // не сохраняем пустые коллекции
@ -103,8 +102,6 @@ public class StorageCollection<T>
} }
writer.Write(value.Key); writer.Write(value.Key);
writer.Write(_separatorForKeyValue); writer.Write(_separatorForKeyValue);
writer.Write(value.Value.GetCollectionType);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.MaxCount); writer.Write(value.Value.MaxCount);
writer.Write(_separatorForKeyValue); writer.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems()) foreach (T? item in value.Value.GetItems())
@ -146,27 +143,28 @@ public class StorageCollection<T>
string strs = ""; string strs = "";
while ((strs = fs.ReadLine()) != null) while ((strs = fs.ReadLine()) != null)
{ {
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4) if (record.Length != 3)
{ {
continue; continue;
} }
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось создать коллекцию");
if (collection == null) if (collection == null)
{ {
throw new Exception("Не удалось создать коллекцию"); throw new Exception("Не удалось создать коллекцию");
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningPropelledArtillery() is T PropelledArtillery) if (elem?.CreateDrawningPropelledArtillery() is T ship)
{ {
try try
{ {
if (collection.Insert(PropelledArtillery) == -1) if (collection.Insert(ship) == -1)
{ {
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
} }
@ -177,7 +175,7 @@ public class StorageCollection<T>
} }
} }
} }
_storages.Add(record[0], collection); _storages.Add(collectionInfo, collection);
} }
} }

View File

@ -0,0 +1,62 @@
using SelfPropelledArtilleryUnit.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.Drawnings;
public class DrawiningPropelledArtilleryEqutables : IEqualityComparer<DrawningPropelledArtillery?>
{
public bool Equals(DrawningPropelledArtillery? x, DrawningPropelledArtillery? y)
{
if (x == null || x.EntityPropelledArtillery == null)
{
return false;
}
if (y == null || y.EntityPropelledArtillery == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityPropelledArtillery.Speed != y.EntityPropelledArtillery.Speed)
{
return false;
}
if (x.EntityPropelledArtillery.Weight != y.EntityPropelledArtillery.Weight)
{
return false;
}
if (x.EntityPropelledArtillery.BodyColor != y.EntityPropelledArtillery.BodyColor)
{
return false;
}
if (x is DrawningSelfPropelledArtilleryUnit && y is DrawningSelfPropelledArtilleryUnit)
{
EntitySelfPropelledArtilleryUnit _x = (EntitySelfPropelledArtilleryUnit)x.EntityPropelledArtillery;
EntitySelfPropelledArtilleryUnit _y = (EntitySelfPropelledArtilleryUnit)x.EntityPropelledArtillery;
if (_x.AdditionalColor != _y.AdditionalColor)
{
return false;
}
if (_x.TurretCannon != _y.TurretCannon)
{
return false;
}
if (_x.LaunchBattery != _y.LaunchBattery)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningPropelledArtillery obj)
{
return obj.GetHashCode();
}
}

View File

@ -96,8 +96,8 @@ public class DrawningPropelledArtillery
protected DrawningPropelledArtillery(int drawningPropelledArtilleryWidth, int drawningPropelledArtilleryHeight):this() protected DrawningPropelledArtillery(int drawningPropelledArtilleryWidth, int drawningPropelledArtilleryHeight):this()
{ {
_drawningPropelledArtilleryWidth = drawningPropelledArtilleryWidth; this._drawningPropelledArtilleryWidth = drawningPropelledArtilleryWidth;
_drawningPropelledArtilleryHeight = drawningPropelledArtilleryHeight; this._drawningPropelledArtilleryHeight = drawningPropelledArtilleryHeight;
} }
public DrawningPropelledArtillery(EntityPropelledArtillery propelledArtillery) : this() public DrawningPropelledArtillery(EntityPropelledArtillery propelledArtillery) : this()
{ {
@ -273,8 +273,5 @@ public class DrawningPropelledArtillery
g.DrawEllipse(pen, _startPosX.Value + 93, _startPosY.Value + 78, 24, 24); g.DrawEllipse(pen, _startPosX.Value + 93, _startPosY.Value + 78, 24, 24);
g.FillRectangle(brush, _startPosX.Value + 0, _startPosY.Value + 65, 120, 13);// g.FillRectangle(brush, _startPosX.Value + 0, _startPosY.Value + 65, 120, 13);//
} }
} }

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.Drawnings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningPropelledArtilleryCompareByColor : IComparer<DrawningPropelledArtillery?>
{
public int Compare(DrawningPropelledArtillery? x, DrawningPropelledArtillery? y)
{
if (x == null || x.EntityPropelledArtillery == null)
{
return 1;
}
if (y == null || y.EntityPropelledArtillery == null)
{
return -1;
}
var bodycolorCompare = x.EntityPropelledArtillery.BodyColor.Name.CompareTo(y.EntityPropelledArtillery.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityPropelledArtillery.Speed.CompareTo(y.EntityPropelledArtillery.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityPropelledArtillery.Weight.CompareTo(y.EntityPropelledArtillery.Weight);
}
}

View File

@ -0,0 +1,38 @@
using SelfPropelledArtilleryUnit.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
/// <summary>
/// Сравнение по типу, скорости, весу
/// </summary>
public class DrawningPropelledArtilleryCompareByType : IComparer<DrawningPropelledArtillery?>
{
public int Compare(DrawningPropelledArtillery? x, DrawningPropelledArtillery? y)
{
if (x == null || x.EntityPropelledArtillery == null)
{
return 1;
}
if (y == null || y.EntityPropelledArtillery == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityPropelledArtillery.Speed.CompareTo(y.EntityPropelledArtillery.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityPropelledArtillery.Weight.CompareTo(y.EntityPropelledArtillery.Weight);
}
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
public class ObjectIsEqualException : ApplicationException
{
public ObjectIsEqualException(int count) : base("В коллекции содержится равный элемент: " + count) { }
public ObjectIsEqualException() : base() { }
public ObjectIsEqualException(string message) : base(message) { }
public ObjectIsEqualException(string message, Exception exception) : base(message, exception) { }
protected ObjectIsEqualException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -30,6 +30,8 @@
{ {
groupBoxTools = new GroupBox(); groupBoxTools = new GroupBox();
panelCompanyTools = new Panel(); panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonSortByType = new Button();
maskedTextBox = new MaskedTextBox(); maskedTextBox = new MaskedTextBox();
buttonAddPropelledArtillery = new Button(); buttonAddPropelledArtillery = new Button();
buttonRefresh = new Button(); buttonRefresh = new Button();
@ -75,6 +77,8 @@
// //
// panelCompanyTools // panelCompanyTools
// //
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(maskedTextBox); panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonAddPropelledArtillery); panelCompanyTools.Controls.Add(buttonAddPropelledArtillery);
panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonRefresh);
@ -83,12 +87,30 @@
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(6, 343); panelCompanyTools.Location = new Point(6, 343);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(200, 213); panelCompanyTools.Size = new Size(188, 236);
panelCompanyTools.TabIndex = 9; panelCompanyTools.TabIndex = 9;
// //
// buttonSortByColor
//
buttonSortByColor.Location = new Point(0, 194);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(188, 23);
buttonSortByColor.TabIndex = 0;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Location = new Point(0, 168);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(188, 23);
buttonSortByType.TabIndex = 1;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.Click += buttonSortByType_Click;
//
// maskedTextBox // maskedTextBox
// //
maskedTextBox.Location = new Point(0, 94); maskedTextBox.Location = new Point(0, 49);
maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(188, 23); maskedTextBox.Size = new Size(188, 23);
maskedTextBox.TabIndex = 0; maskedTextBox.TabIndex = 0;
@ -107,7 +129,7 @@
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(0, 185); buttonRefresh.Location = new Point(0, 140);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(188, 22); buttonRefresh.Size = new Size(188, 22);
buttonRefresh.TabIndex = 6; buttonRefresh.TabIndex = 6;
@ -118,7 +140,7 @@
// buttonRemovePropelledArtillery // buttonRemovePropelledArtillery
// //
buttonRemovePropelledArtillery.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRemovePropelledArtillery.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemovePropelledArtillery.Location = new Point(0, 123); buttonRemovePropelledArtillery.Location = new Point(0, 78);
buttonRemovePropelledArtillery.Name = "buttonRemovePropelledArtillery"; buttonRemovePropelledArtillery.Name = "buttonRemovePropelledArtillery";
buttonRemovePropelledArtillery.Size = new Size(188, 24); buttonRemovePropelledArtillery.Size = new Size(188, 24);
buttonRemovePropelledArtillery.TabIndex = 4; buttonRemovePropelledArtillery.TabIndex = 4;
@ -129,7 +151,7 @@
// buttonGoToCheck // buttonGoToCheck
// //
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(0, 153); buttonGoToCheck.Location = new Point(0, 108);
buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(188, 26); buttonGoToCheck.Size = new Size(188, 26);
buttonGoToCheck.TabIndex = 5; buttonGoToCheck.TabIndex = 5;
@ -340,5 +362,7 @@
private ToolStripMenuItem loadToolStripMenuItem; private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
} }
} }

View File

@ -78,6 +78,11 @@ public partial class FormPropelledArtilleryCollection : Form
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message); _logger.LogError("Ошибка: {Message}", ex.Message);
} }
catch (ObjectIsEqualException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
} }
/// <summary> /// <summary>
@ -196,7 +201,7 @@ public partial class FormPropelledArtilleryCollection : Form
listBoxCollection.Items.Clear(); listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i) for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{ {
string? colName = _storageCollection.Keys?[i]; string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName)) if (!string.IsNullOrEmpty(colName))
{ {
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(colName);
@ -290,6 +295,27 @@ public partial class FormPropelledArtilleryCollection : Form
} }
} }
} }
private void buttonSortByType_Click(object sender, EventArgs e)
{
ComparePropelledArtillery(new DrawningPropelledArtilleryCompareByType());
}
private void ComparePropelledArtillery(IComparer<DrawningPropelledArtillery?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
private void buttonSortByColor_Click(object sender, EventArgs e)
{
ComparePropelledArtillery(new DrawningPropelledArtilleryCompareByColor());
}
} }