首页 > 代码库 > 泛型接口
泛型接口
泛型接口指定实参
public sealed class Point { public Int32 x; public Int32 y; public override string ToString() { return "x: " + x + " y: " + y; } } public class Triangle : IEnumerable<Point> { private Point[] m_triangle; public Triangle(Point[] pArray) { m_triangle = new Point[pArray.Length]; for (Int32 i = 0; i < pArray.Length; i++) { m_triangle[i] = pArray[i]; } } public IEnumerator<Point> GetEnumerator() { return new TriangleEnum(m_triangle); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public sealed class TriangleEnum : IEnumerator<Point> { private Point[] m_vertices; int position = -1; public TriangleEnum(Point[] list) { m_vertices = list; } public Boolean MoveNext() { position++; return position < m_vertices.Length; } public void Reset() { position = -1; } public Point Current { get { try { return m_vertices[position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } Object IEnumerator.Current { get { return Current; } } public void Dispose() { } }
泛型接口未指定实参
internal sealed class ArrayEnumerable<T> : IEnumerable<T> { private T[] m_array; public ArrayEnumerable(T[] list) { m_array = new T[list.Length]; for (Int32 i = 0; i < list.Length; i++) { m_array[i] = list[i]; } } public IEnumerator<T> GetEnumerator() { return new ArrayEnumerator<T>(m_array); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal sealed class ArrayEnumerator<T> : IEnumerator<T> { private T[] m_array; private Int32 m_position = -1; public ArrayEnumerator(T[] list) { m_array = list; } public Boolean MoveNext() { m_position++; return m_position < m_array.Length; } public void Reset() { m_position = -1; } public T Current { get { try { return m_array[m_position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } Object IEnumerator.Current { get { return Current; } } public void Dispose() { } }
测试代码
class GenericInterfaceNoAssign { public static void Go() { Point[] points = new Point[7] { new Point(){x=110, y=220}, new Point(){x=111, y=221}, new Point(){x=112, y=222}, new Point(){x=113, y=223}, new Point(){x=114, y=224}, new Point(){x=115, y=225}, new Point(){x=116, y=226} }; ArrayEnumerable<Point> arrayEn = new ArrayEnumerable<Point>(points); foreach (Point p in arrayEn) { Console.WriteLine(p.ToString()); } } } class GenericInterface { public static void Go() { Point[] points = new Point[3] { new Point(){x=10, y=20}, new Point(){x=11, y=21}, new Point(){x=12, y=22} }; Triangle triangle = new Triangle(points); foreach (Point p in points) { Console.WriteLine(p.ToString()); } } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。