Дабораторная работа №7
This commit is contained in:
parent
ce84c8d6be
commit
128a639927
@ -62,7 +62,7 @@ public abstract class AbstractCompany
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static int operator +(AbstractCompany company, DrawingShip ship)
|
public static int operator +(AbstractCompany company, DrawingShip ship)
|
||||||
{
|
{
|
||||||
return company._collection.Insert(ship);
|
return company._collection.Insert(ship, new DrawingShipEqutables());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -111,4 +111,5 @@ public abstract class AbstractCompany
|
|||||||
protected abstract void SetObjectsPosition();
|
protected abstract void SetObjectsPosition();
|
||||||
|
|
||||||
protected abstract void DrawBackground(Graphics g);
|
protected abstract void DrawBackground(Graphics g);
|
||||||
|
public void Sort(IComparer<DrawingShip?> comparer) => _collection?.CollectionSort(comparer);
|
||||||
}
|
}
|
||||||
|
75
Cruiser/Cruiser/CollectionGenericObjects/CollectionInfo.cs
Normal file
75
Cruiser/Cruiser/CollectionGenericObjects/CollectionInfo.cs
Normal file
@ -0,0 +1,75 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace Cruiser.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();
|
||||||
|
}
|
||||||
|
}
|
@ -8,7 +8,7 @@ namespace Cruiser.CollectionGenericObjects;
|
|||||||
|
|
||||||
public enum CollectionType
|
public enum CollectionType
|
||||||
{
|
{
|
||||||
None = 1,
|
None = 0,
|
||||||
Massive = 1,
|
Massive = 1,
|
||||||
List = 2
|
List = 2
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
using System;
|
using Cruiser.Drawings;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
@ -24,7 +25,7 @@ public interface ICollectionGenericObjects<T>
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="obj"></param>
|
/// <param name="obj"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
int Insert(T obj);
|
int Insert(T obj, IEqualityComparer<T?>? comarer = null);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Добавление в коллекцию по индексу
|
/// Добавление в коллекцию по индексу
|
||||||
@ -32,7 +33,7 @@ public interface ICollectionGenericObjects<T>
|
|||||||
/// <param name="obj"></param>
|
/// <param name="obj"></param>
|
||||||
/// <param name="position"></param>
|
/// <param name="position"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
int Insert(T obj, int position);
|
int Insert(T obj, int position, IEqualityComparer<T?>? comarer = null);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Удаление из коллекции по индесу
|
/// Удаление из коллекции по индесу
|
||||||
@ -58,4 +59,6 @@ public interface ICollectionGenericObjects<T>
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns>Поэлементый вывод элементов коллекции</returns>
|
/// <returns>Поэлементый вывод элементов коллекции</returns>
|
||||||
IEnumerable<T?> GetItems();
|
IEnumerable<T?> GetItems();
|
||||||
|
|
||||||
|
void CollectionSort(IComparer<T?> comparer);
|
||||||
}
|
}
|
||||||
|
@ -1,8 +1,10 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using System.Collections;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
using Cruiser.Drawings;
|
||||||
using Cruiser.Exceptions;
|
using Cruiser.Exceptions;
|
||||||
namespace Cruiser.CollectionGenericObjects;
|
namespace Cruiser.CollectionGenericObjects;
|
||||||
|
|
||||||
@ -53,17 +55,31 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
return _collection[position];
|
return _collection[position];
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Insert(T obj)
|
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
|
||||||
{
|
{
|
||||||
if (Count == _maxCount) throw new CollectionOverflowException();
|
if (Count == _maxCount) throw new CollectionOverflowException();
|
||||||
|
if (comparer != null)
|
||||||
|
{
|
||||||
|
if (_collection.Contains(obj, comparer))
|
||||||
|
{
|
||||||
|
throw new ObjectAlreadyExistsException(obj);
|
||||||
|
}
|
||||||
|
}
|
||||||
_collection.Add(obj);
|
_collection.Add(obj);
|
||||||
return Count;
|
return Count;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Insert(T obj, int position)
|
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
|
||||||
{
|
{
|
||||||
if (Count == _maxCount) throw new CollectionOverflowException();
|
if (Count == _maxCount) throw new CollectionOverflowException();
|
||||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
|
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
|
||||||
|
if (comparer != null)
|
||||||
|
{
|
||||||
|
if (_collection.Contains(obj, comparer))
|
||||||
|
{
|
||||||
|
throw new ObjectAlreadyExistsException(obj);
|
||||||
|
}
|
||||||
|
}
|
||||||
_collection.Insert(position, obj);
|
_collection.Insert(position, obj);
|
||||||
return position;
|
return position;
|
||||||
}
|
}
|
||||||
@ -83,4 +99,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
yield return _collection[i];
|
yield return _collection[i];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void CollectionSort(IComparer<T?> comparer)
|
||||||
|
{
|
||||||
|
_collection.Sort(comparer);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -51,9 +51,19 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
return _collection[position];
|
return _collection[position];
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Insert(T obj)
|
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
|
||||||
{
|
{
|
||||||
for (int i = 0; i < _collection.Length; i++)
|
if (comparer != null)
|
||||||
|
{
|
||||||
|
foreach (T? i in _collection)
|
||||||
|
{
|
||||||
|
if (comparer.Equals(i, obj))
|
||||||
|
{
|
||||||
|
throw new ObjectAlreadyExistsException(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (int i = 0; i < Count; i++)
|
||||||
{
|
{
|
||||||
if (_collection[i] == null)
|
if (_collection[i] == null)
|
||||||
{
|
{
|
||||||
@ -64,9 +74,21 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
throw new CollectionOverflowException();
|
throw new CollectionOverflowException();
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Insert(T obj, int position)
|
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
|
||||||
{
|
{
|
||||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
|
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
|
||||||
|
|
||||||
|
if (comparer != null)
|
||||||
|
{
|
||||||
|
foreach (T? i in _collection)
|
||||||
|
{
|
||||||
|
if (comparer.Equals(i, obj))
|
||||||
|
{
|
||||||
|
throw new ObjectAlreadyExistsException(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (_collection[position] == null)
|
if (_collection[position] == null)
|
||||||
{
|
{
|
||||||
_collection[position] = obj;
|
_collection[position] = obj;
|
||||||
@ -111,6 +133,11 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
yield return _collection[i];
|
yield return _collection[i];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void CollectionSort(IComparer<T?> comparer)
|
||||||
|
{
|
||||||
|
Array.Sort(_collection, comparer);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ -14,12 +14,12 @@ public class StorageCollection<T> where T : DrawingShip
|
|||||||
/// <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>
|
||||||
/// Ключевое слово, с которого должен начинаться файл
|
/// Ключевое слово, с которого должен начинаться файл
|
||||||
@ -29,7 +29,7 @@ public class StorageCollection<T> where T : DrawingShip
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Разделитель для записи ключа и значения элемента словаря
|
/// Разделитель для записи ключа и значения элемента словаря
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private readonly string _separatorForKeyValue = "|";
|
private readonly string _separatorKeyValue = "|";
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Разделитель для записей коллекции данных в файл
|
/// Разделитель для записей коллекции данных в файл
|
||||||
@ -41,7 +41,7 @@ public class StorageCollection<T> where T : DrawingShip
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public StorageCollection()
|
public StorageCollection()
|
||||||
{
|
{
|
||||||
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
|
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -54,43 +54,47 @@ public class StorageCollection<T> where T : DrawingShip
|
|||||||
{
|
{
|
||||||
if (_storages.Count == 0)
|
if (_storages.Count == 0)
|
||||||
{
|
{
|
||||||
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
|
throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения");
|
||||||
}
|
}
|
||||||
if (File.Exists(filename))
|
if (File.Exists(filename))
|
||||||
{
|
{
|
||||||
File.Delete(filename);
|
File.Delete(filename);
|
||||||
}
|
}
|
||||||
StringBuilder sb = new();
|
|
||||||
sb.Append(_collectionKey);
|
|
||||||
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in
|
using (StreamWriter writer = new(filename))
|
||||||
_storages)
|
|
||||||
{
|
{
|
||||||
sb.Append(Environment.NewLine);
|
writer.Write(_collectionKey);
|
||||||
// не сохраняем пустые коллекции
|
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
|
||||||
if (value.Value.Count == 0)
|
|
||||||
{
|
{
|
||||||
continue;
|
writer.Write(Environment.NewLine);
|
||||||
}
|
if (value.Value.Count == 0)
|
||||||
sb.Append(value.Key);
|
|
||||||
sb.Append(_separatorForKeyValue);
|
|
||||||
sb.Append(value.Value.GetCollectionType);
|
|
||||||
sb.Append(_separatorForKeyValue);
|
|
||||||
sb.Append(value.Value.MaxCount);
|
|
||||||
sb.Append(_separatorForKeyValue);
|
|
||||||
foreach (T? item in value.Value.GetItems())
|
|
||||||
{
|
|
||||||
string data = item?.GetDataForSave() ?? string.Empty;
|
|
||||||
if (string.IsNullOrEmpty(data))
|
|
||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
sb.Append(data);
|
|
||||||
sb.Append(_separatorItems);
|
writer.Write(value.Key);
|
||||||
|
writer.Write(_separatorKeyValue);
|
||||||
|
|
||||||
|
writer.Write(value.Value.MaxCount);
|
||||||
|
writer.Write(_separatorKeyValue);
|
||||||
|
|
||||||
|
foreach (T? item in value.Value.GetItems())
|
||||||
|
{
|
||||||
|
string data = item?.GetDataForSave() ?? string.Empty;
|
||||||
|
if (string.IsNullOrEmpty(data))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
writer.Write(data);
|
||||||
|
writer.Write(_separatorItems);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
writer.Close();
|
||||||
|
|
||||||
}
|
}
|
||||||
using FileStream fs = new(filename, FileMode.Create);
|
|
||||||
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
|
|
||||||
fs.Write(info, 0, info.Length);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -102,68 +106,66 @@ public class StorageCollection<T> where T : DrawingShip
|
|||||||
{
|
{
|
||||||
if (!File.Exists(filename))
|
if (!File.Exists(filename))
|
||||||
{
|
{
|
||||||
throw new FileNotFoundException("Файл не существует");
|
throw new FileNotFoundException("Файл не существует!");
|
||||||
}
|
|
||||||
string bufferTextFromFile = "";
|
|
||||||
using (FileStream fs = new(filename, FileMode.Open))
|
|
||||||
{
|
|
||||||
byte[] b = new byte[fs.Length];
|
|
||||||
UTF8Encoding temp = new(true);
|
|
||||||
while (fs.Read(b, 0, b.Length) > 0)
|
|
||||||
{
|
|
||||||
bufferTextFromFile += temp.GetString(b);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
|
|
||||||
StringSplitOptions.RemoveEmptyEntries);
|
|
||||||
if (strs == null || strs.Length == 0)
|
|
||||||
{
|
|
||||||
throw new Exception("В файле нет данных");
|
|
||||||
}
|
|
||||||
if (!strs[0].Equals(_collectionKey))
|
|
||||||
{
|
|
||||||
throw new Exception("В файле неверные данные");
|
|
||||||
}
|
|
||||||
_storages.Clear();
|
|
||||||
foreach (string data in strs)
|
|
||||||
{
|
|
||||||
string[] record = data.Split(_separatorForKeyValue,
|
|
||||||
StringSplitOptions.RemoveEmptyEntries);
|
|
||||||
if (record.Length != 4)
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
CollectionType collectionType =
|
|
||||||
(CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
|
|
||||||
ICollectionGenericObjects<T>? collection =
|
|
||||||
StorageCollection<T>.CreateCollection(collectionType);
|
|
||||||
if (collection == null)
|
|
||||||
{
|
|
||||||
throw new Exception("Не удалось создать коллекцию");
|
|
||||||
}
|
|
||||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
|
||||||
string[] set = record[3].Split(_separatorItems,
|
|
||||||
StringSplitOptions.RemoveEmptyEntries);
|
|
||||||
foreach (string elem in set)
|
|
||||||
{
|
|
||||||
if (elem?.CreateDrawingShip() is T ship)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
if (collection.Insert(ship) == -1)
|
|
||||||
{
|
|
||||||
throw new ConstraintException("Объект не удалось добавить в коллекцию: " + record[3]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (CollectionOverflowException ex)
|
|
||||||
{
|
|
||||||
throw new DataException("Коллекция переполнена", ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_storages.Add(record[0], collection);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
using (StreamReader reader = new(filename))
|
||||||
|
{
|
||||||
|
string line = reader.ReadLine();
|
||||||
|
if (line == null || line.Length == 0)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("В файле нет данных");
|
||||||
|
}
|
||||||
|
if (!line.Equals(_collectionKey))
|
||||||
|
{
|
||||||
|
throw new InvalidDataException("В файле неверные данные");
|
||||||
|
}
|
||||||
|
|
||||||
|
_storages.Clear();
|
||||||
|
while ((line = reader.ReadLine()) != null)
|
||||||
|
{
|
||||||
|
string[] record = line.Split(_separatorKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
if (record.Length != 3)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
//CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
|
||||||
|
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
|
||||||
|
throw new Exception("Не удалось определить информацию о коллекции:" + record[0]);
|
||||||
|
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ?? throw new Exception("Не удалось создать коллекцию");
|
||||||
|
if (collection == null)
|
||||||
|
{
|
||||||
|
throw new InvalidCastException("Не удалось определить тип коллекции: " + record[1]);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
collection.MaxCount = Convert.ToInt32(record[1]);
|
||||||
|
|
||||||
|
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
foreach (string elem in set)
|
||||||
|
{
|
||||||
|
if (elem?.CreateDrawingShip() is T ship)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (collection.Insert(ship) < 0)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (CollectionOverflowException ex)
|
||||||
|
{
|
||||||
|
throw new CollectionOverflowException("Коллекция переполнена", ex);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_storages.Add(collectionInfo, collection);
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -188,19 +190,23 @@ public class StorageCollection<T> where T : DrawingShip
|
|||||||
/// <param name="collectionType">Тип коллекции</param>
|
/// <param name="collectionType">Тип коллекции</param>
|
||||||
public void AddCollection(string name, CollectionType collectionType)
|
public void AddCollection(string name, CollectionType collectionType)
|
||||||
{
|
{
|
||||||
if (_storages.ContainsKey(name))// || collectionType == CollectionType.None)
|
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
|
||||||
|
|
||||||
|
if (name == null || _storages.ContainsKey(collectionInfo))
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (collectionType)
|
switch (collectionType)
|
||||||
{
|
{
|
||||||
|
case CollectionType.None:
|
||||||
|
return;
|
||||||
case CollectionType.Massive:
|
case CollectionType.Massive:
|
||||||
_storages[name] = new MassiveGenericObjects<T>();
|
_storages[collectionInfo] = new MassiveGenericObjects<T>();
|
||||||
break;
|
return;
|
||||||
case CollectionType.List:
|
case CollectionType.List:
|
||||||
_storages[name] = new ListGenericObjects<T>();
|
_storages[collectionInfo] = new ListGenericObjects<T>();
|
||||||
break;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -210,9 +216,10 @@ public class StorageCollection<T> where T : DrawingShip
|
|||||||
/// <param name="name">Название коллекции</param>
|
/// <param name="name">Название коллекции</param>
|
||||||
public void DelCollection(string name)
|
public void DelCollection(string name)
|
||||||
{
|
{
|
||||||
if (_storages.ContainsKey(name) && name != null)
|
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
|
||||||
|
if (_storages.ContainsKey(collectionInfo))
|
||||||
{
|
{
|
||||||
_storages.Remove(name);
|
_storages.Remove(collectionInfo);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -225,11 +232,12 @@ public class StorageCollection<T> where T : DrawingShip
|
|||||||
{
|
{
|
||||||
get
|
get
|
||||||
{
|
{
|
||||||
if (_storages.ContainsKey(name))
|
CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty);
|
||||||
|
if (!_storages.ContainsKey(collectionInfo))
|
||||||
{
|
{
|
||||||
return _storages[name];
|
return null;
|
||||||
}
|
}
|
||||||
return null;
|
return _storages[collectionInfo];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
34
Cruiser/Cruiser/Drawings/DrawingShipCompareByColor.cs
Normal file
34
Cruiser/Cruiser/Drawings/DrawingShipCompareByColor.cs
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace Cruiser.Drawings;
|
||||||
|
|
||||||
|
public class DrawingShipCompareByColor : IComparer<DrawingShip?>
|
||||||
|
{
|
||||||
|
public int Compare(DrawingShip? x, DrawingShip? y)
|
||||||
|
{
|
||||||
|
if (x == null || x.EntityShip == null)
|
||||||
|
{
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (y == null || y.EntityShip == null)
|
||||||
|
{
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
var bodycolorCompare = x.EntityShip.BodyColor.Name.CompareTo(y.EntityShip.BodyColor.Name);
|
||||||
|
if (bodycolorCompare != 0)
|
||||||
|
{
|
||||||
|
return bodycolorCompare;
|
||||||
|
}
|
||||||
|
var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed);
|
||||||
|
if (speedCompare != 0)
|
||||||
|
{
|
||||||
|
return speedCompare;
|
||||||
|
}
|
||||||
|
return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight);
|
||||||
|
}
|
||||||
|
}
|
33
Cruiser/Cruiser/Drawings/DrawingShipCompareByType.cs
Normal file
33
Cruiser/Cruiser/Drawings/DrawingShipCompareByType.cs
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Cruiser.Drawings;
|
||||||
|
|
||||||
|
namespace Cruiser.CollectionGenericObjects;
|
||||||
|
|
||||||
|
public class DrawingShipCompareByType : IComparer<DrawingShip?>
|
||||||
|
{
|
||||||
|
public int Compare(DrawingShip? x, DrawingShip? y)
|
||||||
|
{
|
||||||
|
if (x == null || x.EntityShip == null)
|
||||||
|
{
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (y == null || y.EntityShip == null)
|
||||||
|
{
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
if (x.GetType().Name != y.GetType().Name)
|
||||||
|
{
|
||||||
|
return x.GetType().Name.CompareTo(y.GetType().Name);
|
||||||
|
}
|
||||||
|
var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed);
|
||||||
|
if (speedCompare != 0)
|
||||||
|
{
|
||||||
|
return speedCompare;
|
||||||
|
}
|
||||||
|
return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight);
|
||||||
|
}
|
||||||
|
}
|
56
Cruiser/Cruiser/Drawings/DrawingShipEqutables.cs
Normal file
56
Cruiser/Cruiser/Drawings/DrawingShipEqutables.cs
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
using Cruiser.Entities;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Security.Cryptography.Xml;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace Cruiser.Drawings;
|
||||||
|
|
||||||
|
public class DrawingShipEqutables : IEqualityComparer<DrawingShip?>
|
||||||
|
{
|
||||||
|
public bool Equals(DrawingShip? x, DrawingShip? y)
|
||||||
|
{
|
||||||
|
if (x == null || x.EntityShip == null)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (y == null || y.EntityShip == null)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (x.GetType().Name != y.GetType().Name)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (x.EntityShip.Speed != y.EntityShip.Speed)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (x.EntityShip.Weight != y.EntityShip.Weight)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (x.EntityShip.BodyColor != y.EntityShip.BodyColor)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (x is DrawingCruiser && y is DrawingCruiser)
|
||||||
|
{
|
||||||
|
EntityCruiser crx = (EntityCruiser)x.EntityShip;
|
||||||
|
EntityCruiser cry = (EntityCruiser)y.EntityShip;
|
||||||
|
if (crx.Helicopter != cry.Helicopter) return false;
|
||||||
|
if (crx.BodyKit != cry.BodyKit) return false;
|
||||||
|
if (crx.Arms != cry.Arms) return false;
|
||||||
|
if (crx.AdditionalColor != cry.AdditionalColor) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int GetHashCode([DisallowNull] DrawingShip obj)
|
||||||
|
{
|
||||||
|
return obj.GetHashCode();
|
||||||
|
}
|
||||||
|
}
|
19
Cruiser/Cruiser/Exceptions/ObjectAlreadyExistsException.cs
Normal file
19
Cruiser/Cruiser/Exceptions/ObjectAlreadyExistsException.cs
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Runtime.Serialization;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace Cruiser.Exceptions;
|
||||||
|
|
||||||
|
[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) { }
|
||||||
|
}
|
39
Cruiser/Cruiser/FormShipCollection.Designer.cs
generated
39
Cruiser/Cruiser/FormShipCollection.Designer.cs
generated
@ -52,6 +52,8 @@
|
|||||||
LoadToolStripMenuItem = new ToolStripMenuItem();
|
LoadToolStripMenuItem = new ToolStripMenuItem();
|
||||||
saveFileDialog = new SaveFileDialog();
|
saveFileDialog = new SaveFileDialog();
|
||||||
openFileDialog = new OpenFileDialog();
|
openFileDialog = new OpenFileDialog();
|
||||||
|
buttonSortByColor = new Button();
|
||||||
|
buttonSortByType = new Button();
|
||||||
groupBoxTools.SuspendLayout();
|
groupBoxTools.SuspendLayout();
|
||||||
panelCompanyTools.SuspendLayout();
|
panelCompanyTools.SuspendLayout();
|
||||||
panelStorage.SuspendLayout();
|
panelStorage.SuspendLayout();
|
||||||
@ -68,7 +70,7 @@
|
|||||||
groupBoxTools.Dock = DockStyle.Right;
|
groupBoxTools.Dock = DockStyle.Right;
|
||||||
groupBoxTools.Location = new Point(852, 28);
|
groupBoxTools.Location = new Point(852, 28);
|
||||||
groupBoxTools.Name = "groupBoxTools";
|
groupBoxTools.Name = "groupBoxTools";
|
||||||
groupBoxTools.Size = new Size(324, 742);
|
groupBoxTools.Size = new Size(324, 841);
|
||||||
groupBoxTools.TabIndex = 0;
|
groupBoxTools.TabIndex = 0;
|
||||||
groupBoxTools.TabStop = false;
|
groupBoxTools.TabStop = false;
|
||||||
groupBoxTools.Text = "Инструменты";
|
groupBoxTools.Text = "Инструменты";
|
||||||
@ -97,15 +99,17 @@
|
|||||||
//
|
//
|
||||||
// panelCompanyTools
|
// panelCompanyTools
|
||||||
//
|
//
|
||||||
|
panelCompanyTools.Controls.Add(buttonSortByColor);
|
||||||
|
panelCompanyTools.Controls.Add(buttonSortByType);
|
||||||
panelCompanyTools.Controls.Add(buttonRefresh);
|
panelCompanyTools.Controls.Add(buttonRefresh);
|
||||||
panelCompanyTools.Controls.Add(buttonGoToCheck);
|
panelCompanyTools.Controls.Add(buttonGoToCheck);
|
||||||
panelCompanyTools.Controls.Add(buttonAddShip);
|
panelCompanyTools.Controls.Add(buttonAddShip);
|
||||||
panelCompanyTools.Controls.Add(buttonRemoveShip);
|
panelCompanyTools.Controls.Add(buttonRemoveShip);
|
||||||
panelCompanyTools.Controls.Add(maskedTextBox);
|
panelCompanyTools.Controls.Add(maskedTextBox);
|
||||||
panelCompanyTools.Enabled = false;
|
panelCompanyTools.Enabled = false;
|
||||||
panelCompanyTools.Location = new Point(12, 446);
|
panelCompanyTools.Location = new Point(12, 415);
|
||||||
panelCompanyTools.Name = "panelCompanyTools";
|
panelCompanyTools.Name = "panelCompanyTools";
|
||||||
panelCompanyTools.Size = new Size(300, 300);
|
panelCompanyTools.Size = new Size(300, 414);
|
||||||
panelCompanyTools.TabIndex = 2;
|
panelCompanyTools.TabIndex = 2;
|
||||||
//
|
//
|
||||||
// buttonRefresh
|
// buttonRefresh
|
||||||
@ -248,7 +252,7 @@
|
|||||||
pictureBoxCollection.Dock = DockStyle.Fill;
|
pictureBoxCollection.Dock = DockStyle.Fill;
|
||||||
pictureBoxCollection.Location = new Point(0, 28);
|
pictureBoxCollection.Location = new Point(0, 28);
|
||||||
pictureBoxCollection.Name = "pictureBoxCollection";
|
pictureBoxCollection.Name = "pictureBoxCollection";
|
||||||
pictureBoxCollection.Size = new Size(852, 742);
|
pictureBoxCollection.Size = new Size(852, 841);
|
||||||
pictureBoxCollection.TabIndex = 1;
|
pictureBoxCollection.TabIndex = 1;
|
||||||
pictureBoxCollection.TabStop = false;
|
pictureBoxCollection.TabStop = false;
|
||||||
//
|
//
|
||||||
@ -288,17 +292,38 @@
|
|||||||
// saveFileDialog
|
// saveFileDialog
|
||||||
//
|
//
|
||||||
saveFileDialog.Filter = "txt file | *.txt";
|
saveFileDialog.Filter = "txt file | *.txt";
|
||||||
|
|
||||||
//
|
//
|
||||||
// openFileDialog
|
// openFileDialog
|
||||||
//
|
//
|
||||||
openFileDialog.Filter = "txt file | *.txt";
|
openFileDialog.Filter = "txt file | *.txt";
|
||||||
//
|
//
|
||||||
|
// buttonSortByColor
|
||||||
|
//
|
||||||
|
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||||
|
buttonSortByColor.Location = new Point(19, 335);
|
||||||
|
buttonSortByColor.Name = "buttonSortByColor";
|
||||||
|
buttonSortByColor.Size = new Size(240, 52);
|
||||||
|
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(19, 277);
|
||||||
|
buttonSortByType.Name = "buttonSortByType";
|
||||||
|
buttonSortByType.Size = new Size(240, 52);
|
||||||
|
buttonSortByType.TabIndex = 7;
|
||||||
|
buttonSortByType.Text = "Сортировка по типу";
|
||||||
|
buttonSortByType.UseVisualStyleBackColor = true;
|
||||||
|
buttonSortByType.Click += ButtonSortByType_Click;
|
||||||
|
//
|
||||||
// FormShipCollection
|
// FormShipCollection
|
||||||
//
|
//
|
||||||
AutoScaleDimensions = new SizeF(8F, 20F);
|
AutoScaleDimensions = new SizeF(8F, 20F);
|
||||||
AutoScaleMode = AutoScaleMode.Font;
|
AutoScaleMode = AutoScaleMode.Font;
|
||||||
ClientSize = new Size(1176, 770);
|
ClientSize = new Size(1176, 869);
|
||||||
Controls.Add(pictureBoxCollection);
|
Controls.Add(pictureBoxCollection);
|
||||||
Controls.Add(groupBoxTools);
|
Controls.Add(groupBoxTools);
|
||||||
Controls.Add(menuStrip);
|
Controls.Add(menuStrip);
|
||||||
@ -343,5 +368,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;
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -39,6 +39,11 @@ public partial class FormShipCollection : Form
|
|||||||
MessageBox.Show("Не удалось добавить объект");
|
MessageBox.Show("Не удалось добавить объект");
|
||||||
_logger.LogError("Ошибка: В коллекции превышено допустимое количество");
|
_logger.LogError("Ошибка: В коллекции превышено допустимое количество");
|
||||||
}
|
}
|
||||||
|
catch (ObjectAlreadyExistsException)
|
||||||
|
{
|
||||||
|
MessageBox.Show("Такой объект уже существует");
|
||||||
|
_logger.LogError("Ошибка: такой объект уже существует {0}", ship);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -105,7 +110,7 @@ public partial class FormShipCollection : Form
|
|||||||
{
|
{
|
||||||
DrawingShip? ship = null;
|
DrawingShip? ship = null;
|
||||||
int counter = 100;
|
int counter = 100;
|
||||||
while(ship == null)
|
while (ship == null)
|
||||||
{
|
{
|
||||||
ship = _company.GetRandomObject();
|
ship = _company.GetRandomObject();
|
||||||
counter--;
|
counter--;
|
||||||
@ -136,27 +141,27 @@ public partial class FormShipCollection : Form
|
|||||||
|
|
||||||
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
|
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
|
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonMassive.Checked && !radioButtonList.Checked))
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
return;
|
_logger.LogWarning("Неверно введены данные для создания коллекции");
|
||||||
}
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
CollectionType collectionType = CollectionType.None;
|
CollectionType collectionType = CollectionType.None;
|
||||||
if (radioButtonList.Checked)
|
if (radioButtonMassive.Checked)
|
||||||
{
|
{
|
||||||
collectionType = CollectionType.List;
|
collectionType = CollectionType.Massive;
|
||||||
}
|
}
|
||||||
else if (radioButtonMassive.Checked)
|
else if (radioButtonList.Checked)
|
||||||
{
|
{
|
||||||
collectionType = CollectionType.Massive;
|
collectionType = CollectionType.List;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
_logger.LogInformation($"Добавлена коллекция - {textBoxCollectionName.Text}");
|
||||||
RefreshListBoxItems();
|
RefreshListBoxItems();
|
||||||
_logger.LogInformation("Добавлена коллекция: {Collection} типа: {Type}", textBoxCollectionName.Text, collectionType);
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private void ButtonCollectionDel_Click(object sender, EventArgs e)
|
private void ButtonCollectionDel_Click(object sender, EventArgs e)
|
||||||
{
|
{
|
||||||
@ -180,7 +185,7 @@ public partial class FormShipCollection : 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);
|
||||||
@ -225,9 +230,9 @@ public partial class FormShipCollection : Form
|
|||||||
_storageCollection.SaveData(saveFileDialog.FileName);
|
_storageCollection.SaveData(saveFileDialog.FileName);
|
||||||
MessageBox.Show("Сохранение прошло успешно",
|
MessageBox.Show("Сохранение прошло успешно",
|
||||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||||
_logger.LogInformation("Сохранение в файл {filename}", saveFileDialog.FileName);
|
_logger.LogInformation("Сохранение в файл {filename}", saveFileDialog.FileName);
|
||||||
}
|
}
|
||||||
catch(Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show(ex.Message, "Результат",
|
MessageBox.Show(ex.Message, "Результат",
|
||||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
@ -259,4 +264,18 @@ public partial class FormShipCollection : Form
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareShips(new DrawingShipCompareByType());
|
||||||
|
|
||||||
|
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareShips(new DrawingShipCompareByColor());
|
||||||
|
|
||||||
|
private void CompareShips(IComparer<DrawingShip?> comparer)
|
||||||
|
{
|
||||||
|
if (_company == null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_company.Sort(comparer);
|
||||||
|
pictureBoxCollection.Image = _company.Show();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user