This commit is contained in:
zum 2024-05-13 12:23:36 +04:00
parent 4f8b615375
commit b84a8b7655
6 changed files with 145 additions and 28 deletions

View File

@ -0,0 +1,76 @@
using ProjectStormTrooper.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

@ -61,6 +61,10 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{ {
throw new CollectionOverflowException(); throw new CollectionOverflowException();
} }
if(_collection.Contains(obj,comparer))
{
throw new ObjectExistsException();
}
_collection.Add(obj); _collection.Add(obj);
return true; return true;
@ -76,6 +80,10 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{ {
throw new PositionOutOfCollectionException(); throw new PositionOutOfCollectionException();
} }
if (_collection.Contains(obj, comparer))
{
throw new ObjectExistsException();
}
_collection.Insert(position, obj); _collection.Insert(position, obj);
return true; return true;
} }

View File

@ -66,6 +66,10 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
{ {
int index = Array.IndexOf(_collection, null); int index = Array.IndexOf(_collection, null);
if (_collection.Contains(obj, comparer))
{
throw new ObjectExistsException();
}
if(index >= 0) if(index >= 0)
{ {
_collection[index] = obj; _collection[index] = obj;
@ -82,6 +86,10 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
{ {
throw new PositionOutOfCollectionException(); throw new PositionOutOfCollectionException();
} }
if (_collection.Contains(obj, comparer))
{
throw new ObjectExistsException();
}
for (int i = position; i < _collection.Length; i++) for (int i = position; i < _collection.Length; i++)
{ {
if (_collection[i] == null) if (_collection[i] == null)
@ -131,7 +139,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
if(_collection?.Length > 0) if(_collection?.Length > 0)
{ {
Array.Sort(_collection, comparer); Array.Sort(_collection, comparer);
//Array.Reverse(_collection); Array.Reverse(_collection);
} }
} }

View File

@ -1,6 +1,7 @@
using ProjectStormTrooper.CollectionGenericObjects; using ProjectStormTrooper.CollectionGenericObjects;
using ProjectStormTrooper.Drawnings; using ProjectStormTrooper.Drawnings;
using ProjectStormTrooper.Exceptions; using ProjectStormTrooper.Exceptions;
using System.Collections.Generic;
using System.Text; using System.Text;
/// <summary> /// <summary>
@ -13,12 +14,12 @@ 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>
@ -40,7 +41,7 @@ public class StorageCollection<T>
/// </summary> /// </summary>
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
} }
/// <summary> /// <summary>
@ -50,17 +51,18 @@ 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)
{ {
if(name == null || _storages.ContainsKey(name)) { return; } CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
switch(collectionType) if (collectionInfo.Name == null || _storages.ContainsKey(collectionInfo) ){ return; }
switch(collectionInfo.CollectionType)
{ {
case CollectionType.None: case CollectionType.None:
return; return;
case CollectionType.Massive: case CollectionType.Massive:
_storages.Add(name, new MassiveGenericObjects<T> { }); _storages.Add(collectionInfo, new MassiveGenericObjects<T> { });
return; return;
case CollectionType.List: case CollectionType.List:
_storages.Add(name, new ListGenericObjects<T> { }); _storages.Add(collectionInfo, new ListGenericObjects<T> { });
return; return;
} }
@ -72,8 +74,9 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
public void DelCollection(string name) public void DelCollection(string name)
{ {
if (name == null || !_storages.ContainsKey(name)) { return; } CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
_storages.Remove(name); if (collectionInfo.Name == null || !_storages.ContainsKey(collectionInfo)) { return; }
_storages.Remove(collectionInfo);
} }
/// <summary> /// <summary>
@ -81,12 +84,13 @@ public class StorageCollection<T>
/// </summary> /// </summary>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
/// <returns></returns> /// <returns></returns>
public ICollectionGenericObjects<T>? this[string name] public ICollectionGenericObjects<T>? this[string collectionName]
{ {
get get
{ {
if (name == null || !_storages.ContainsKey(name)) { return null; } CollectionInfo collectionInfo = new CollectionInfo(collectionName,CollectionType.None,"");
return _storages[name]; if (collectionInfo == null || !_storages.ContainsKey(collectionInfo)) { return null; }
return _storages[collectionInfo];
} }
} }
/// <summary> /// <summary>
@ -111,7 +115,7 @@ public class StorageCollection<T>
using FileStream fs = new(filename, FileMode.Create); using FileStream fs = new(filename, FileMode.Create);
using StreamWriter streamWriter = new StreamWriter(fs); using StreamWriter streamWriter = new StreamWriter(fs);
streamWriter.Write(_collectionKey); streamWriter.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages) foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{ {
streamWriter.Write(Environment.NewLine); streamWriter.Write(Environment.NewLine);
// не сохраняем пустые коллекции // не сохраняем пустые коллекции
@ -122,8 +126,6 @@ public class StorageCollection<T>
streamWriter.Write(value.Key); streamWriter.Write(value.Key);
streamWriter.Write(_separatorForKeyValue); streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.GetCollectionType);
streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.MaxCount); streamWriter.Write(value.Value.MaxCount);
streamWriter.Write(_separatorForKeyValue); streamWriter.Write(_separatorForKeyValue);
@ -171,18 +173,17 @@ public class StorageCollection<T>
while (!streamReader.EndOfStream) while (!streamReader.EndOfStream)
{ {
string[] record = streamReader.ReadLine().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = streamReader.ReadLine().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); if(record.Length != 3)
if(record.Length != 4)
{ {
continue; continue;
} }
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType) ?? CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new InvalidCastException("Не удалось определить тип коллекции:" + record[1]); ; throw new Exception("Не удалось определить информацию коллекции:" + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось определить тип коллекции:" + record[1]);
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningWarPlane() is T warPlane) if (elem?.CreateDrawningWarPlane() is T warPlane)
@ -201,7 +202,7 @@ public class StorageCollection<T>
} }
} }
_storages.Add(record[0], collection); _storages.Add(collectionInfo, collection);
} }
} }

View File

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

View File

@ -64,6 +64,11 @@ namespace ProjectStormTrooper
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}"); _logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
} }
catch(ObjectExistsException ex)
{
MessageBox.Show("Такой объект есть в коллекции");
_logger.LogWarning($"Добавление существующего объекта: {ex.Message}");
}
} }
@ -202,7 +207,6 @@ namespace ProjectStormTrooper
{ {
collectionType = CollectionType.List; collectionType = CollectionType.List;
} }
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text}"); _logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text}");
RerfreshListBoxItems(); RerfreshListBoxItems();
@ -240,7 +244,7 @@ namespace ProjectStormTrooper
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);