-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathCustomCollection.cs
99 lines (77 loc) · 2.81 KB
/
CustomCollection.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
interface IReadOnlyArray<out T> : IEnumerable<T>, IEnumerable ,IEnumerator<T>,IEnumerator
{
// your custom implementations
T this[int index] { get; }
}
public struct ReadOnlyArray<T> : IReadOnlyArray<T>
{
private readonly T[] _array;
public int Length => _array.Length;
// Enumerators are positioned before the first element
// until the first MoveNext() call
int position; // Enumerator
public ReadOnlyArray(T[] array)
{
position = -1;
_array = array;
}
// such a nice pointer shot!
public ref readonly T IndexReference(int index)
{
return ref this._array[index];
}
public static implicit operator ReadOnlyArray<T>(T[]? array) =>
new ReadOnlyArray<T>(array ?? new T[1]);
// IEnumerable<T>
public IEnumerator<T> GetEnumerator()
{
return new ReadOnlyArray<T>(_array);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
// IEnumerator<T>
public bool MoveNext()
{
position++;
return (position < _array.Length);
}
public void Reset()
{
position = -1;
}
public void Dispose()
{
// extra disposing!
}
object IEnumerator.Current => Current;
public T Current
{
get
{
try
{
return _array[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
public readonly T this[int index] => _array[index];
}
LoopInForEach list = new();
foreach (var item in list)
{
Console.WriteLine(item); // valid
}
var refCheck = new int[] { 1, 2, 3 };
IReadOnlyArray<int> readOnlyArray = (ReadOnlyArray<int>) refCheck; // valid
ReadOnlyArray<int> roArray = refCheck; // valid
public class LoopInForEach
{
private readonly List<string> internalList = new List<string>() { "hello", "world" };
public List<string>.Enumerator GetEnumerator() => internalList.GetEnumerator();
}