/// <summary>
/// 自定义泛型可迭代类型
/// </summary>
/// <example>
/// This code shows how to build a instance of <see cref="SelfEnumerable"/>:
/// <code>
/// var enumerable = new SelfEnumerable<typeparam name="T">Person</typeparam>5);
/// enumerable.Add(new Person() { Name = "xfh", Age = 27 });
/// </code>
/// </example>
/// <descript>
/// 灵感来自:
/// The foreach statement executes a statement or a block of statements for each element in an instance of the type
/// that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable<T> interface.
/// The foreach statement is not limited to those types and can be applied to an instance of any type that satisfies the following cond
/// 1. has the public parameterless GetEnumerator method whose return type is either class, struct, or interface type,
/// 2. the return type of the GetEnumerator method has the public Current property and the public parameterless MoveNext metho
/// whose return type is Boolean.
/// 参考了:
/// https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/Span.cs
/// https://docs.microsoft.com/en-us/dotnet/csharp/iterators
/// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/foreach-in
/// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/yield
/// </descript>
public class SelfEnumerable<T>
{
private readonly int _capacity;
private T[] _innerArray;
private int _addIndex = 0;
public SelfEnumerable(int capacity)
{
_capacity = capacity;
_innerArray = new T[capacity];
}
/// <summary>
/// 可迭代对象中存储的对象数
/// </summary>
/// <value>auto-property</value>
public int Count { get; private set; } = 0;
public T this[int index] => _innerArray[index];
/// <summary>
/// 向可迭代对象中添加元素
/// </summary>
/// <remarks>当添加的元素数超过<see cref="_capacity"/>的值时,新添加的元素会覆盖之前的值</remarks>
public void Add(T item)
{
if (_addIndex > _capacity - 1)
{
_addIndex = 0;
}
else
{
Count++;
}
_innerArray[_addIndex] = item;
_addIndex++;
}
public SelfEnumerator GetEnumerator() => new SelfEnumerator(this);
public class SelfEnumerator
{
private readonly SelfEnumerable<T> _selfEnumerable;
private int _seekIndex = -1;
internal SelfEnumerator(SelfEnumerable<T> selfEnumerable)
{
_selfEnumerable = selfEnumerable;
}
public T Current => _selfEnumerable[_seekIndex];
public bool MoveNext()
{
_seekIndex++;
if (_seekIndex > _selfEnumerable.Count - 1)
{
return false;
}
return true;
}
}
}
C# 自定义可迭代类型
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 1. 前言: 说点废话,时间紧的请直接跳过,看后面的实现。 尽管本人很反感 C 语言中的宏定义,特别是滥用宏定义经...
- c语言中的基本并不能满足我们日常使用,这在其他面向对象的解决方式是采用类定义的方式解决,那么在c语言中,giant...
- 自从8月22日晚上讲了微课“从现在改变未来”,到今天已经是第十八天了,出乎大家意料的是,我居然在课后每天都花二到三...