.NET 中是否有任何列表/集合类的行为类似于滚动日志文件?用户可以向其中追加元素,但如果超过最大容量,列表将自动删除旧元素。
我还想访问列表中的任何元素,例如列表[102]等
这是一个简单的实现:
public class RollingList<T> : IEnumerable<T>
{
private readonly LinkedList<T> _list = new LinkedList<T>();
public RollingList(int maximumCount)
{
if (maximumCount <= 0)
throw new ArgumentException(null, nameof(maximumCount));
MaximumCount = maximumCount;
}
public int MaximumCount { get; }
public int Count => _list.Count;
public void Add(T value)
{
if (_list.Count == MaximumCount)
{
_list.RemoveFirst();
}
_list.AddLast(value);
}
public T this[int index]
{
get
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException();
return _list.Skip(index).First();
}
}
public IEnumerator<T> GetEnumerator() => _list.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)