asp.net如何使Vector类支持IEnumerable接口
这问题确实太初级了,好久没用这个,忘了分请在①处添加代码,使得Vector类支持IEnumerable接口。 提示:实现GetEnumerator 方法,这需要定义一个实现了IEnumerator接口的辅助类。 using System; using System.Collections.Generic; namespace CollectionDemo { class Vector : IEnumerable { public double X; public double Y; public double Z; public Vector(double x, double y, double z) { X = x; Y = y; Z = z; } //① } class Program { static void Main(string[] args) { Vector vec = new Vector(30, 100, 60); foreach (double v in vec) { Console.WriteLine(v); } } } } 输出的结果为: 30 100 60
书上的例子都是用于对象,foreach怎么用于double类型,而且是在vec对象中 后要重新绑定一下数据了,恩,是要把所有的查出来,不过无所谓,内部项目,放局域网上用,懒的写分页了~
using System; using System.Collections.Generic; using System.Linq; using System.Collections; using System.Text;
namespace ConsoleApplication3 { class Vector : IEnumerable { public double X; public double Y; public double Z; public Vector(double x, double y, double z) { X = x; Y = y; Z = z; } public IEnumerator GetEnumerator() { return new MyStringEnumerator(X,Y,Z); } } public class MyStringEnumerator : IEnumerator { private double[] arr; private int index = -1; public MyStringEnumerator(double x,double y,double z) { arr = new double[3] {x,y,z}; } public object Current { get { return arr[index]; } }
public bool MoveNext() { index++; if (index < arr.Length) { return true; } else { return false; } }
public void Reset() { index = -1; } } }
|