我以前从未做过收藏。我试图在互联网上找到解决方案,以及他们必须添加的接口才能工作。
我添加了我能在网上找到的所有内容。
public class RecipeObjectCollection : ICollection<RecipeObject>, IList<RecipeObject>, IEnumerable<RecipeObject>, IEnumerable, IList, ICollection
{
public struct Enumerator : IEnumerator<RecipeObject>, IDisposable, IEnumerator
{
private RecipeObjectCollection collection;
private RecipeObject current;
private int next;
private readonly int version;
public RecipeObject Current => this.current;
...
我显然无法将所有内容放在示例代码中,但在其余代码中只有继承的函数或方法。
一切都没有后顾之忧,除了我注意到当我完成我的收集时,ICollection.Count和IList.this [int index]中有一个循环
object IList.this[int index]
{
get
{
return this[index];
}
set
{
this.CheckIndex(index);
try
{
this[index] = (RecipeObject)((object)value);
return;
}
catch (InvalidCastException) { }
catch (NullReferenceException) { }
throw new ArgumentException();
}
}
int ICollection.Count
{
get
{
return this.Count;
}
}
在调试模式下,我没有找到为什么这个循环开始以及如何或一次停止的原因。尽管这个循环,我的程序运行良好。即使我怀疑它,我也不知道它是否正常。
我可以添加代码或其他任何东西,如果它缺乏可以给出答案或至少一个线索。
虽然我觉得没有足够的信息来给出具体的答案,但我猜你可能会将无限递归称为这个问题的循环。
如果是这样,如果对象IList.this [int index] setter方法中的以下行,我不会感到惊讶:
this[index] = (RecipeObject)((object)value);
将无限地递归调用对象IList.this [int index] setter方法,直到达到最大递归深度。
可能是你想要做的事情
this.collection[index] = (RecipeObject)((object)value);"
在那条线而不是?
您不需要实现所有方法。如果你想使用一个集合,你可以像这样声明它。
public class RecipeObjectCollection: List<RecipeObject>
{
//......
}
public class RecipeObject
{
//......
}
那么你可以利用List对象上的现有方法。没有额外的麻烦实施额外的方法。您解释的奇怪行为可能是其中一种方法的实施结果。