Created
July 15, 2014 06:58
-
-
Save kuanyingchou/de5dc2bf69cf6a2069bd to your computer and use it in GitHub Desktop.
This file contains hidden or 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 UnityEngine; | |
using System.Collections; | |
using System.Collections.Generic; | |
public class TestYield : MonoBehaviour | |
{ | |
public void Start() { | |
IntList list = new IntList(); | |
list.Add(3); | |
list.Add(5); | |
list.Add(7); | |
printIntList(list); | |
list[0] = 1; | |
//printIntList(list); | |
//for (int i = 0; i < 100; i++) | |
//{ | |
// list.Add(i); | |
//} | |
printIntList(list); | |
} | |
private void printIntList(IntList list) | |
{ | |
//foreach (int i in list) | |
//{ | |
// Debug.Log(i); | |
//} | |
IEnumerator enumerator = list.GetEnumerator(); | |
while (enumerator.MoveNext()) { | |
object curr = enumerator.Current; | |
Debug.Log(curr); | |
} | |
} | |
class IntList : IEnumerable { | |
static readonly int INITIAL_SLOTS = 10; | |
int[] values = new int[INITIAL_SLOTS]; | |
int next = 0; | |
public void Add(int value) | |
{ | |
values[next++] = value; | |
if (next >= values.Length) { | |
Expand(); | |
} | |
} | |
public int Get(int index) | |
{ | |
if (index >= next || index < 0) throw new System.ArgumentException(); | |
return values[index]; | |
} | |
public void Set(int index, int value) { | |
if (index > next || index < 0) throw new System.ArgumentException(); | |
values[index] = value; | |
} | |
public int this[int index] | |
{ | |
get { return Get(index); } | |
set { Set(index, value); } | |
} | |
private void Expand() | |
{ | |
int[] newValues = new int[values.Length * 2]; | |
for (int i = 0; i < values.Length; i++) | |
{ | |
newValues[i] = values[i]; | |
} | |
values = newValues; | |
} | |
public int Count { get { return next; } } | |
public IEnumerator GetEnumerator() | |
{ | |
//return new IntListEnum(this); | |
for (int i = 0; i < next; i++) | |
{ | |
yield return values[i]; | |
} | |
} | |
public class IntListEnum : IEnumerator | |
{ | |
int index = -1; | |
IntList list; | |
public IntListEnum(IntList list) | |
{ | |
this.list = list; | |
} | |
object IEnumerator.Current { | |
get { | |
try | |
{ | |
return list.values[index]; | |
} | |
catch (System.ArgumentOutOfRangeException) | |
{ | |
return new System.InvalidOperationException(); | |
} | |
} | |
} | |
public bool MoveNext() | |
{ | |
index++; | |
if (index >= list.Count) | |
{ | |
return false; | |
} | |
else | |
{ | |
return true; | |
} | |
} | |
public void Reset() | |
{ | |
index = -1; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment