Создание коллекции объектов

This commit is contained in:
Роман Пермяков 2024-03-09 14:58:24 +04:00
parent 17ea81733b
commit 216d07bec8
2 changed files with 128 additions and 0 deletions

View File

@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.CollectionGenericObjects
{
public interface ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// кол-во элем
/// </summary>
int Count { get; }
/// <summary>
/// установить макс элем
/// </summary>
int SetMaxCount { set; }
/// <summary>
/// вставить
/// </summary>
/// <param name="obj">добавляемый объект</param>
/// <returns></returns>
bool Insert(T obj);
/// <summary>
/// вставить по позиции
/// </summary>
/// <param name="obj">добавляемый объект</param>
/// <param name="position">индекс</param>
/// <returns></returns>
bool Insert(T obj, int position);
/// <summary>
/// удаление
/// </summary>
/// <param name="position">индекс</param>
/// <returns></returns>
bool Remove(int position);
/// <summary>
/// получение объекта по позиции
/// </summary>
/// <param name="position">индекс</param>
/// <returns></returns>
T? Get(int position);
}
}

View File

@ -0,0 +1,82 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.CollectionGenericObjects
{
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
private T?[] _collection;
public int Count => _collection.Length;
public int SetMaxCount { set { if (value > 0) { _collection = new T?[value]; } } }
public MassiveGenericObjects()
{
_collection = Array.Empty<T?>();
}
public T? Get(int position)
{
if (position < 0 || position >= _collection.Length) return null;
return _collection[position];
}
public bool Insert(T obj)
{
for (int i = 0; i < _collection.Length; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return true;
}
}
return false;
}
public bool Insert(T obj, int position)
{
if (position < 0 || position >= _collection.Length) { return false; }
if (_collection[position] == null)
{
_collection[position] = obj;
return true;
}
else
{
for (int i = position + 1; i < _collection.Length; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return true;
}
}
for (int i = position - 1; i >= 0; i--)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return true;
}
}
}
return false;
}
public bool Remove(int position)
{
if (position < 0 || position >= _collection.Length) { return false;}
_collection[position] = null;
return true;
}
}
}