【发布时间】:2020-01-24 05:31:03
【问题描述】:
我已经修复了 Vector 类。请看下面的代码。在我的主要功能之外,我给出了以下功能。我不允许更改此功能。
private static bool CheckIntSequence<T>(T[] certificate, Vector<T> vector)
{
if (certificate.Length != vector.Count) return false;
int counter = 0;
foreach (T value in vector)
{
if (!value.Equals(certificate[counter])) return false;
counter++;
}
return true;
}
在主函数中,我创建了一个矢量类对象,并使用以下序列(2、6、8、5、5、1、8、5、3、5、7、1、4、9)添加了元素vector.Add(2) 方法。现在,当我通过异常调用 CheckIntSequence 函数时,因为向量长度为 15。
Console.WriteLine("\nTest D: Check the content of the Vector<int> by traversing it via 'foreach' statement ");
if (!CheckIntSequence(new int[] { 2, 6, 8, 5, 5, 1, 8, 5, 3, 5, 7, 1, 4, 9 }, vector)) throw new Exception("The 'foreach' statement produces an incorrect sequence of integers");
Console.WriteLine(" :: SUCCESS");
正如我所提到的,我只能在矢量类中进行更改。我尝试了几件事来在 CheckIntSequence 中取得成功,但没有运气。有人可以看看并帮助我在我的矢量课程中做错了什么。
public class Vector<T> : IEnumerable<T>
{
private const int DEFAULT_CAPACITY = 10;
private T[] data;
public int Count = 0;
public int Capacity
{ get { return data.Length; } }
public Vector(int capacity)
{ data = new T[capacity]; }
public Vector() : this(DEFAULT_CAPACITY) { }
public T this[int index]
{ get
{
if (index >= Count || index < 0) throw new IndexOutOfRangeException();
return data[index];
}
set
{
if (index >= Count || index < 0) throw new IndexOutOfRangeException();
data[index] = value;
}
}
public int IndexOf(T element)
{
for (var i = 0; i < Count; i++)
{
if (data[i].Equals(element)) return i;
}
return -1;
}
private void ExtendData(int extraCapacity)
{
T[] newData = new T[Capacity + extraCapacity];
for (int i = 0; i < Count; i++) newData[i] = data[i];
data = newData;
}
public void Add(T element)
{
if (Count == Capacity) ExtendData(DEFAULT_CAPACITY);
data[Count++] = element;
}
public IEnumerator<T> GetEnumerator()
{
return new VectorEnumerator(data);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public class VectorEnumerator : IEnumerator<T>
{
private T[] _data;
private int curIndex;
private T current;
public VectorEnumerator(T[] list)
{
_data = list;
curIndex = -1;
current = default(T);
}
public bool MoveNext()
{
if (++curIndex >= _data.Length)
{ return false; }
else
{ current = _data[curIndex]; }
return true;
}
public void Reset() { curIndex = -1; }
void IDisposable.Dispose() { }
public T Current {get { return current; }}
object IEnumerator.Current {get { return Current; }}
}
}
【问题讨论】:
-
旁注:
public void Dispose() {throw new NotImplementedException();}- 请不要这样做;如果你对Dispose有什么都没有,那么什么都不做:public void Dispose() {;} -
坦率地说,
vector.First()会在这里为您省去很多痛苦;还有 - 这看起来像是对一系列内置类型的拙劣模仿...... -
强调@DmitryBychenko的观点:调用
Dispose是这里的正常操作——它是foreach的一部分;所以:如果你不解决这个问题,foreach也不会工作
标签: c# .net ienumerable enumerable enumerator