请在①处添加代码,使得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对象中C#IEnumerableforeach

解决方案 »

  1.   

    太伤心了,没人帮忙啊,还是自己做出来了
    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;
            }
        }
    }