/ Published in: C#
This is a demo how to create a Linear List with APTs make using of Generics, Indexer and the IEnumerator Interface. With this APTs it is possible to create a high performace, type safety class which is available for different control loops techniques and so on.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
using System; using System.Text; using System.Collections; using System.Collections.Generic; namespace MyOwnGeneric { class OwnObject<T> { private T content; private OwnObject<T> next; public T Content { get { return content; } set { content = value; } } public OwnObject<T> Next { get { return next; } set { next = value; } } public override string ToString() { return content.ToString(); } } class LinList<T> : IEnumerable<T> { private OwnObject<T> first; private OwnObject<T> last; public OwnObject<T> First { get { return first; } set { first = value; } } public OwnObject<T> Last { get { return last; } set { last = value; } } public void Add(OwnObject<T> item) { if (first == null) { first = item; last = item; } else { last.Next = item; last = item; } } //function to count items in LinList public int Count() { int counter = 0; OwnObject<T> position = first; while (position != null) { counter++; position = position.Next; } return counter; } //function to get the content at a fix position in LinList public T GetItem(int pos) { int counter = 0; OwnObject<T> position = first; //T result = null not possible because value type T result = default(T); while (position != null) { if (counter == pos) { result = position.Content; break; } counter++; position = position.Next; } return result; } public override string ToString() { string result = ""; OwnObject<T> position = first; while (position != null) { result += position.ToString(); if (position.Next != null) result += " - "; position = position.Next; } return result; } //indexer public T this[int index] { get { return this.GetItem(index); } } //interface IEnumerable public IEnumerator<T> GetEnumerator() { OwnObject<T> position = first; while (position != null) { yield return position.Content; position = position.Next; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } class Program { static void Main(string[] args) { testcont.Content = "test"; testcont2.Content = "test2"; testcont3.Content = "test3"; test.Add(testcont); test.Add(testcont2); test.Add(testcont3); //using the interface of IEnumerable foreach (string item in test) { Console.WriteLine(item); } //using the indexer and the item counter for (int i = 0; i < test.Count(); i++) { Console.WriteLine(test[i]); } } } }