Powiel możliwe:
Implementing C# IEnumerable<T> for a LinkedList classWdrażanie IEnumerable do mojego obiektu
Po poszukiwaniach w internecie na kilka godzin teraz ja wciąż nie mogę zrozumieć, jak IEnumerable
/IEnumerator
działa i jak go wdrożyć .
Skonstruowałem prosty od zera LinkedList
, ale teraz chcę zaimplementować IEnumerable
, abym mógł go wyłączyć. Jak mogę to zrobić?
class Program
{
LL myList = new LL();
static void Main()
{
var gogo = new Program();
}
public Program()
{
myList.Add("test");
myList.Add("test1");
foreach (var item in myList) //This doesn't work because I havn't implemented Ienumerable
Console.WriteLine(item);
Console.Read();
}
}
class LL
{
private LLNode first;
public void Add(string s)
{
if (this.first == null)
this.first = new LLNode() { Value = s };
else
{
var node = this.first;
while (node.Next != null)
node = node.Next;
node.Next = new LLNode() { Value = s };
}
}
class LLNode
{
public string Value { get; set; }
public LLNode Next { get; set; }
}
Czy jesteś pewien, że próbowałeś? – Nahum
[tutaj] (http://codebetter.com/davidhayden/2005/03/08/implementing-ienumerable-and-ienumerator-on-your-custom-objects/) jest * nie jest dobrym samouczkiem dotyczącym implementacji 'IEnumerable' na niestandardowa klasa. [Tutaj] (http://www.codeproject.com/Articles/474678/A-Beginners-Tutorial-on-Implementing-Ynumerable-I) jest lepszy. – NominSim
Zauważ, że technicznie nie * nie trzeba * wdrażać 'IEnumerable' aby użyć twojej klasy z' foreach'-loop ... – sloth