Last active
January 16, 2023 10:39
-
-
Save qluana7/743334f7b764c9efd2417c03689e8189 to your computer and use it in GitHub Desktop.
뒤와 앞이 연결된 배열입니다. 기존의 Array는 Length를 넘어가거나 음수를 넣으면 IndexOutOfRangeException를 던지지만, SpanArray는 그에 해당하는 값을 반환합니다. Ex) { 1, 2, 3, 4 }[5] = 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace CustomArray | |
{ | |
#region SpanArray<T> | |
public class SpanArray<T> : IEnumerable<T> | |
{ | |
#region Constructor | |
public SpanArray(int index) : this(new T[index]) { } | |
public SpanArray(IEnumerable<T> array) | |
{ | |
arr = array.ToArray(); | |
Length = arr.Length; | |
} | |
#endregion | |
#region Field & Property | |
private T[] arr; | |
public int Length { get; } | |
#endregion | |
#region Indexer | |
public T this[int i] | |
{ | |
get => arr[GetIndexer(i)]; | |
set => arr[GetIndexer(i)] = value; | |
} | |
#endregion | |
#region Method | |
private int GetIndexer(int i) | |
{ | |
var r = i % Length; | |
if (i >= 0) | |
return r; | |
else | |
{ | |
var c = Length - Math.Abs(r); | |
if (c == Length) | |
return 0; | |
else | |
return c; | |
} | |
} | |
public IEnumerator<T> GetEnumerator() | |
{ | |
return ((IEnumerable<T>)arr).GetEnumerator(); | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
{ | |
return arr.GetEnumerator(); | |
} | |
#endregion | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment