PIbd-14_Pruidze_I.K_Simple_.../ProjectCruiser/CollectionGenericObj/ListGenObj.cs
2024-06-15 18:06:35 +04:00

96 lines
2.1 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
namespace ProjectCruiser.CollectionGenericObj;
// Параметризованный набор объектов
public class ListGenObj<T> : ICollectionGenObj<T>
where T : class
{
// Список объектов, которые храним
private List<T?> _collection;
// Максимально допустимое число объектов в списке
private int _maxCount;
public int Count => _collection.Count;
public int MaxCount
{
get { return _maxCount; }
set
{
if (value > 0)
{
if (_collection.Count == 0) _collection = new List<T>(value);
else _collection.Capacity = value; // instead of resizing
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
public ListGenObj()
{
_collection = new();
}
public T? GetItem(int position)
{
if (position >= Count || position < 0)
{
return null;
}
return _collection[position];
}
public int Insert(T? obj)
{
if (Count >= _maxCount || obj == null)
{
return -1;
}
_collection.Add(obj);
return Count;
}
public int Insert(T? obj, int position)
{
if (position >= _maxCount || Count >= _maxCount ||
position < 0 || _collection[position] != null
|| obj == null)
{
return -1;
}
_collection.Insert(position, obj);
return position;
}
public T? Remove(int position)
{
if (position >= Count || position < 0)
// on the other positions items don't exist
{
return null;
}
T? item = _collection[position];
_collection.RemoveAt(position);
return item;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
}